<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\SalesRepresentativeModel;
use App\Models\SalesTargetModel;
use App\Models\SalesTerritoryModel;
use Modules\Sale\Services\SalesTargetCommissionService;

class TargetController extends BaseController
{
    protected SalesTargetModel $targets;
    protected SalesRepresentativeModel $reps;
    protected SalesTerritoryModel $territories;
    protected SalesTargetCommissionService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->targets     = new SalesTargetModel();
        $this->reps        = new SalesRepresentativeModel();
        $this->territories = new SalesTerritoryModel();
        $this->service     = new SalesTargetCommissionService();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;
        $repId  = $this->request->getGet('rep_id') ?: null;

        $targets = $this->targets
            ->scopeForList($search ?: null, $status, $repId ? (int) $repId : null)
            ->orderBy('sales_targets.period_start', 'DESC')
            ->findAll();

        return view('Modules\Sale\Views\targets\index', array_merge($this->baseViewData(), [
            'title'   => 'Targets',
            'targets' => $targets,
            'reps'    => $this->reps->getActive(),
            'filters' => ['search' => $search, 'status' => $status, 'repId' => $repId],
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\targets\create', array_merge($this->baseViewData(), [
            'title'       => 'New Target',
            'reps'        => $this->reps->getActive(),
            'territories' => $this->territories->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'sales_rep_id'  => 'required|is_natural_no_zero',
            'period_start'  => 'required|valid_date',
            'period_end'    => 'required|valid_date',
            'target_amount' => 'required|decimal',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->createTarget($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/targets')->with('success', 'Target created.');
    }

    public function editForm(int $id)
    {
        $target = $this->targets->find($id);
        if (! $target) {
            return redirect()->to('/sale/targets')->with('error', 'Target not found.');
        }

        return view('Modules\Sale\Views\targets\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Target',
            'target'      => $target,
            'reps'        => $this->reps->getActive(),
            'territories' => $this->territories->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'sales_rep_id'  => 'required|is_natural_no_zero',
            'period_start'  => 'required|valid_date',
            'period_end'    => 'required|valid_date',
            'target_amount' => 'required|decimal',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->updateTarget($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/targets')->with('success', 'Target updated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->deleteTarget($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/sale/targets')->with('error', $result['error']);
        }

        return redirect()->to('/sale/targets')->with('success', 'Target deleted.');
    }
}
