<?php

class SettlementController extends Controller
{
    private Settlement $settlements;
    private Driver $drivers;

    public function __construct()
    {
        $this->settlements = new Settlement();
        $this->drivers = new Driver();
    }

    public function index(): void
    {
        Auth::requireRole(['owner', 'admin', 'accountant']);
        $search = trim($_GET['search'] ?? '');
        $settlements = $this->settlements->all($search ?: null);
        $this->view('settlements/index', compact('settlements', 'search'));
        clear_old();
    }

    public function create(): void
    {
        Auth::requireRole(['owner', 'admin', 'accountant']);
        $settlement = null;
        $drivers = $this->drivers->all();
        $loads = $this->settlements->payableLoads();
        $nextNumber = $this->settlements->nextNumber();
        $calculatedLoad = !empty($_GET['load_id']) ? $this->settlements->calculateForLoad((int) $_GET['load_id']) : null;
        $this->view('settlements/create', compact('settlement', 'drivers', 'loads', 'nextNumber', 'calculatedLoad'));
    }

    public function store(): void
    {
        Auth::requireRole(['owner', 'admin', 'accountant']);
        Csrf::verify();
        if (empty($_POST['driver_id']) || (float) ($_POST['gross_amount'] ?? 0) <= 0) {
            set_old($_POST);
            $this->flash('danger', 'Driver and gross amount are required.');
            $this->redirect('/settlements/create');
        }
        $id = $this->settlements->create($_POST);
        $accounting = new Accounting();
        $accounting->postSettlement($id);
        if (($_POST['status'] ?? 'pending') === 'paid') {
            $record = $this->settlements->find($id);
            $accounting->postSettlementPayment($id, (float) ($record['net_amount'] ?? 0), date('Y-m-d'));
        }
        log_activity('settlement_created', 'Created driver settlement');
        $this->flash('success', 'Settlement created successfully.');
        $this->redirect('/settlements');
    }

    public function markPaid(): void
    {
        Auth::requireRole(['owner', 'admin', 'accountant']);
        Csrf::verify();
        $id = (int) ($_POST['id'] ?? 0);
        $record = $this->settlements->find($id);
        if (!$record) {
            $this->flash('danger', 'Settlement not found.');
            $this->redirect('/settlements');
        }
        $this->settlements->markPaid($id);
        $accounting = new Accounting();
        $accounting->postSettlement($id);
        $accounting->postSettlementPayment($id, (float) $record['net_amount'], date('Y-m-d'));
        log_activity('settlement_paid', 'Marked settlement as paid');
        $this->flash('success', 'Settlement marked as paid.');
        $this->redirect('/settlements');
    }

    public function delete(): void
    {
        Auth::requireRole(['owner', 'admin', 'accountant']);
        Csrf::verify();
        $id = (int) ($_POST['id'] ?? 0);
        $record = $this->settlements->find($id);
        if (!$record) {
            $this->flash('danger', 'Settlement not found.');
            $this->redirect('/settlements');
        }
        $posted = (int) Database::connection()->query("SELECT COUNT(*) FROM journal_entries WHERE source_type='driver_settlement' AND source_id=" . $id)->fetchColumn();
        if ($record['status'] === 'paid' || $posted > 0) {
            $this->flash('danger', 'Posted or paid settlements cannot be deleted.');
            $this->redirect('/settlements');
        }
        $this->settlements->delete($id);
        log_activity('settlement_deleted', 'Deleted settlement');
        $this->flash('success', 'Settlement deleted successfully.');
        $this->redirect('/settlements');
    }

    public function pdf(): void
    {
        Auth::requireLogin();
        $record=$this->settlements->find((int)($_GET['id']??0));
        if(!$record){$this->flash('danger','Settlement not found.');$this->redirect('/settlements');}
        $user=Auth::user();
        if(($user['role']??'')==='driver' && (int)$record['driver_id']!==(int)($user['driver_id']??0)){http_response_code(403);require app_path('Views/errors/403.php');exit;}
        if(($user['role']??'')!=='driver' && !in_array($user['role'],['owner','admin','accountant'],true)){http_response_code(403);require app_path('Views/errors/403.php');exit;}
        $pdf=new SimplePdf();$pdf->rect(36,710,540,50,true,0.93);$companyX=50;$logoRelative=setting('company_logo','');if($logoRelative&&$pdf->image(base_path($logoRelative),50,716,44,36))$companyX=105;$pdf->text($companyX,742,setting('company_name',APP_NAME)?:APP_NAME,17,true);$pdf->text($companyX,724,'Driver Settlement Statement',10);$pdf->text(430,742,$record['settlement_number'],12,true);$pdf->text(430,724,date_display($record['created_at']),8);
        $pdf->text(40,684,'DRIVER & LOAD',10,true);$pdf->line(40,678,572,678);$y=658;foreach([['Driver',$record['driver_name']?:'-'],['Load',$record['load_number']?:'-'],['Pay Method',readable_status($record['pay_type']??'')],['Driver Rate',(string)($record['driver_rate']??0)],['Load Revenue',money($record['load_rate']??0)],['Miles',(string)($record['miles']??0)]] as$r){$pdf->text(45,$y,$r[0],9,true);$pdf->text(175,$y,$r[1],9);$y-=23;}
        $pdf->rect(310,510,262,132,false);$pdf->text(325,616,'SETTLEMENT SUMMARY',10,true);$pdf->text(325,590,'Gross Earnings',9);$pdf->text(490,590,money($record['gross_amount']),9);$pdf->text(325,564,'Deductions',9);$pdf->text(490,564,'- '.money($record['deductions']),9);$pdf->line(325,550,557,550);$pdf->text(325,526,'NET PAY',12,true);$pdf->text(485,526,money($record['net_amount']),12,true);
        $pdf->text(40,470,'PAYMENT STATUS',10,true);$pdf->line(40,464,572,464);$pdf->text(45,440,readable_status($record['status']),11,true);$pdf->text(180,440,$record['paid_at']?'Paid '.datetime_display($record['paid_at']):'Payment pending',9);
        $pdf->text(40,390,'NOTES',10,true);$pdf->line(40,384,572,384);$pdf->wrappedText(45,362,$record['notes']?:'No additional notes.',515,9,13,false,8);
        $pdf->line(40,110,250,110);$pdf->text(40,95,'Driver acknowledgement',8);$pdf->line(360,110,572,110);$pdf->text(360,95,'Authorized approval',8);$pdf->text(40,45,setting('invoice_terms','')?:'Generated by the operations platform.',8);$out=$pdf->output();header('Content-Type: application/pdf');header('Content-Disposition: attachment; filename="'.$record['settlement_number'].'.pdf"');header('Content-Length: '.strlen($out));echo$out;exit;
    }

}
