<?php

namespace Modules\Sale\Controllers;

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

class CommissionController extends BaseController
{
    protected SalesCommissionModel $commissions;
    protected SalesRepresentativeModel $reps;
    protected SalesTargetCommissionService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->commissions = new SalesCommissionModel();
        $this->reps        = new SalesRepresentativeModel();
        $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;

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\commissions\create', array_merge($this->baseViewData(), [
            'title' => 'New Commission',
            'reps'  => $this->reps->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',
            'base_amount'  => 'required|decimal',
            'rate_percent' => 'required|decimal',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

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

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

        return view('Modules\Sale\Views\commissions\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Commission',
            'commission' => $commission,
            'reps'       => $this->reps->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',
            'base_amount'  => 'required|decimal',
            'rate_percent' => 'required|decimal',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->updateCommission($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/commissions')->with('success', 'Commission updated.');
    }

    public function approve(int $id)
    {
        $result = $this->service->approveCommission($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Commission approved.');
    }

    public function markPaid(int $id)
    {
        $result = $this->service->markCommissionPaid($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Commission marked as paid.');
    }

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

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