<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class InvoiceController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','accountant']);
    }

    public function index(): void
    {
        $status = $_GET['status'] ?? '';
        $conditions = ['1=1']; $params = [];
        if ($status) { $conditions[]='i.status=?'; $params[]=$status; }
        $where = implode(' AND ',$conditions);
        $invoices = $this->db->fetchAll(
            "SELECT i.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, u.unit_number, p.name AS property_name
             FROM invoices i
             JOIN tenants t ON t.id=i.tenant_id
             JOIN units u ON u.id=i.unit_id
             JOIN properties p ON p.id=u.property_id
             WHERE $where ORDER BY i.due_date DESC", $params
        );
        $summary = [
            'total_billed' => (float)$this->db->fetchColumn("SELECT COALESCE(SUM(total_amount),0) FROM invoices"),
            'total_paid'   => (float)$this->db->fetchColumn("SELECT COALESCE(SUM(paid_amount),0) FROM invoices"),
            'overdue'      => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM invoices WHERE status='overdue'"),
            'overdue_amt'  => (float)$this->db->fetchColumn("SELECT COALESCE(SUM(balance),0) FROM invoices WHERE status='overdue'"),
        ];
        $this->adminView('invoice.index', compact('invoices','status','summary') + ['title'=>'Invoices']);
    }

    public function generate(): void
    {
        $this->verifyCsrf();
        $month = $this->input('month', date('Y-m'));
        [$year,$mon] = explode('-', $month);
        $periodFrom = "$year-$mon-01";
        $periodTo   = date('Y-m-t', strtotime($periodFrom));
        $dueDate    = $periodFrom;
        $leases     = $this->db->fetchAll("SELECT * FROM leases WHERE status='active'");
        $created    = 0;
        foreach ($leases as $lease) {
            $exists = $this->db->fetch("SELECT id FROM invoices WHERE lease_id=? AND period_from=?", [$lease['id'],$periodFrom]);
            if ($exists) continue;
            $vatAmt = $lease['vat_applicable'] ? $lease['monthly_rent'] * VAT_RATE : 0;
            $total  = $lease['monthly_rent'] - $lease['discount_amount'] + $vatAmt;
            $invNum = 'INV-'.date('Y').'-'.str_pad((int)$this->db->fetchColumn("SELECT COUNT(*)+1 FROM invoices"), 5,'0',STR_PAD_LEFT);
            $this->db->insert('invoices', [
                'invoice_number' => $invNum,
                'lease_id'       => $lease['id'],
                'tenant_id'      => $lease['tenant_id'],
                'unit_id'        => $lease['unit_id'],
                'period_from'    => $periodFrom,
                'period_to'      => $periodTo,
                'due_date'       => $dueDate,
                'rent_amount'    => $lease['monthly_rent'],
                'discount'       => $lease['discount_amount'],
                'vat_amount'     => $vatAmt,
                'total_amount'   => $total,
                'paid_amount'    => 0,
                'status'         => 'sent',
                'created_by'     => (int)$_SESSION['user_id'],
                'created_at'     => date('Y-m-d H:i:s'),
                'updated_at'     => date('Y-m-d H:i:s'),
            ]);
            $created++;
        }
        Helper::setFlash('success', "$created invoice(s) generated for $month.");
        $this->redirect(APP_URL.'/admin/invoices');
    }

    public function pdf(string $id): void
    {
        $invoice = $this->db->fetch(
            "SELECT i.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, t.phone, t.address AS tenant_address,
                    u.unit_number, u.unit_type, p.name AS property_name, p.address AS property_address
             FROM invoices i JOIN tenants t ON t.id=i.tenant_id JOIN units u ON u.id=i.unit_id JOIN properties p ON p.id=u.property_id WHERE i.id=?", [$id]
        );
        if (!$invoice) { $this->abort(404); return; }
        $settings = array_column($this->db->fetchAll("SELECT `key`,`value` FROM settings"), 'value','key');
        header('Content-Type: text/html; charset=utf-8');
        $this->adminView('invoice.pdf', compact('invoice','settings') + ['title'=>'Invoice '.$invoice['invoice_number']], '');
    }
}
