<?php

namespace Modules\Contracts\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\ContractMilestoneModel;
use App\Models\ContractModel;

class ContractLifecycleController extends BaseController
{
    protected ContractModel $contracts;
    protected CompanyModel $companies;
    protected ContractMilestoneModel $milestones;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->contracts  = new ContractModel();
        $this->companies  = new CompanyModel();
        $this->milestones = new ContractMilestoneModel();
    }

    public function active()
    {
        $search    = trim((string) $this->request->getGet('q'));
        $type      = $this->request->getGet('contract_type') ?: null;
        $companyId = $this->request->getGet('company_id') ?: null;

        $rows = $this->contracts
            ->scopeForList(
                $search ?: null,
                'active',
                $type,
                $companyId ? (int) $companyId : null
            )
            ->orderBy('contracts.end_date', 'ASC')
            ->orderBy('contracts.id', 'DESC')
            ->paginate(20);

        return view('Modules\Contracts\Views\lifecycle\active', array_merge($this->baseViewData(), [
            'title'     => 'Active Contracts',
            'contracts' => $rows,
            'pager'     => $this->contracts->pager,
            'companies' => $this->companies->getActive(),
            'filters'   => [
                'search'    => $search,
                'type'      => $type,
                'companyId' => $companyId,
            ],
        ]));
    }

    public function schedule()
    {
        $search = trim((string) $this->request->getGet('q'));
        $month  = trim((string) $this->request->getGet('month'));
        if ($month === '' || ! preg_match('/^\d{4}-\d{2}$/', $month)) {
            $month = date('Y-m');
        }

        $monthStart = $month . '-01';
        $monthEnd   = date('Y-m-t', strtotime($monthStart));

        $contracts = $this->contracts
            ->scopeForList($search ?: null)
            ->whereIn('contracts.status', ['draft', 'active'])
            ->groupStart()
                ->where('contracts.start_date <=', $monthEnd)
                ->groupStart()
                    ->where('contracts.end_date >=', $monthStart)
                    ->orWhere('contracts.end_date', null)
                ->groupEnd()
            ->groupEnd()
            ->orderBy('contracts.start_date', 'ASC')
            ->orderBy('contracts.id', 'ASC')
            ->findAll();

        $milestones = $this->milestones
            ->select('contract_milestones.*, contracts.number AS contract_number, contracts.title AS contract_title, companies.name AS company_name')
            ->join('contracts', 'contracts.id = contract_milestones.contract_id')
            ->join('companies', 'companies.id = contracts.company_id', 'left')
            ->where('contract_milestones.due_date >=', $monthStart)
            ->where('contract_milestones.due_date <=', $monthEnd)
            ->orderBy('contract_milestones.due_date', 'ASC')
            ->findAll();

        return view('Modules\Contracts\Views\lifecycle\schedule', array_merge($this->baseViewData(), [
            'title'      => 'Contract Schedule',
            'contracts'  => $contracts,
            'milestones' => $milestones,
            'month'      => $month,
            'filters'    => ['search' => $search, 'month' => $month],
        ]));
    }

    public function renewals()
    {
        $search     = trim((string) $this->request->getGet('q'));
        $withinDays = (int) ($this->request->getGet('within') ?: 90);
        if (! in_array($withinDays, [30, 60, 90, 180], true)) {
            $withinDays = 90;
        }

        $today = date('Y-m-d');
        $rows  = $this->contracts
            ->scopeForRenewals($search ?: null, $withinDays, $today)
            ->orderBy('contracts.end_date', 'ASC')
            ->paginate(20);

        return view('Modules\Contracts\Views\lifecycle\renewals', array_merge($this->baseViewData(), [
            'title'      => 'Renewals',
            'contracts'  => $rows,
            'pager'      => $this->contracts->pager,
            'today'      => $today,
            'withinDays' => $withinDays,
            'filters'    => [
                'search' => $search,
                'within' => $withinDays,
            ],
        ]));
    }

    public function expiryAlerts()
    {
        $filter = $this->request->getGet('filter') ?: '30';
        $search = trim((string) $this->request->getGet('q'));
        $today  = date('Y-m-d');

        if (! in_array($filter, ['expired', '7', '30', '90'], true)) {
            $filter = '30';
        }

        $summary = (new ContractModel())->expiryAlertSummary($today);

        $rows = $this->contracts
            ->scopeForExpiryAlerts($search ?: null, $filter, $today)
            ->orderBy('contracts.end_date', $filter === 'expired' ? 'DESC' : 'ASC')
            ->paginate(20);

        return view('Modules\Contracts\Views\lifecycle\expiry_alerts', array_merge($this->baseViewData(), [
            'title'     => 'Expiry Alerts',
            'contracts' => $rows,
            'pager'     => $this->contracts->pager,
            'summary'   => $summary,
            'filter'    => $filter,
            'today'     => $today,
            'filters'   => [
                'search' => $search,
                'filter' => $filter,
            ],
        ]));
    }
}
