<?php
namespace App\Controllers;

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

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

    public function index(): void
    {
        $status = $_GET['status'] ?? '';
        $conditions = ['1=1']; $params = [];
        if ($status) { $conditions[]='l.status=?'; $params[]=$status; }
        $where = implode(' AND ',$conditions);
        $leases = $this->db->fetchAll(
            "SELECT l.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, t.phone,
                    u.unit_number, p.name AS property_name
             FROM leases l
             JOIN tenants t ON t.id=l.tenant_id
             JOIN units u ON u.id=l.unit_id
             JOIN properties p ON p.id=l.property_id
             WHERE $where ORDER BY l.created_at DESC", $params
        );
        $this->adminView('lease.index', compact('leases','status') + ['title'=>'Lease Agreements']);
    }

    public function create(): void
    {
        $tenants    = $this->db->fetchAll("SELECT id, CONCAT(tenant_code,' - ',first_name,' ',last_name) AS name FROM tenants WHERE status='active' ORDER BY first_name");
        $units      = $this->db->fetchAll("SELECT u.id, CONCAT(p.name,' - Unit ',u.unit_number,' (',u.unit_type,')') AS name, u.monthly_rent, u.security_deposit FROM units u JOIN properties p ON p.id=u.property_id WHERE u.status='available' ORDER BY p.name,u.unit_number");
        $properties = $this->db->fetchAll("SELECT id,name FROM properties WHERE status='active' ORDER BY name");
        $this->adminView('lease.form', compact('tenants','units','properties') + ['title'=>'New Lease','lease'=>null]);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $leaseNum = 'LSE-'.date('Y').'-'.str_pad((int)$this->db->fetchColumn("SELECT COUNT(*)+1 FROM leases"), 4,'0',STR_PAD_LEFT);
        $data = [
            'lease_number'       => $leaseNum,
            'tenant_id'          => (int)$this->input('tenant_id'),
            'unit_id'            => (int)$this->input('unit_id'),
            'property_id'        => (int)$this->input('property_id'),
            'start_date'         => $this->input('start_date'),
            'end_date'           => $this->input('end_date'),
            'monthly_rent'       => (float)$this->input('monthly_rent',0),
            'security_deposit'   => (float)$this->input('security_deposit',0),
            'advance_payment'    => (float)$this->input('advance_payment',0),
            'payment_frequency'  => $this->input('payment_frequency','monthly'),
            'payment_due_day'    => (int)$this->input('payment_due_day',1),
            'grace_period_days'  => (int)$this->input('grace_period_days',7),
            'late_fee_percent'   => (float)$this->input('late_fee_percent',0),
            'vat_applicable'     => $this->input('vat_applicable') ? 1 : 0,
            'discount_amount'    => (float)$this->input('discount_amount',0),
            'utilities_included' => $this->input('utilities_included') ? 1 : 0,
            'terms_conditions'   => $this->input('terms_conditions','') ?: null,
            'status'             => $this->input('status','pending'),
            'auto_renew'         => $this->input('auto_renew') ? 1 : 0,
            'created_by'         => (int)$_SESSION['user_id'],
            'created_at'         => date('Y-m-d H:i:s'),
            'updated_at'         => date('Y-m-d H:i:s'),
        ];
        try {
            $id = $this->db->insert('leases', $data);
            // If activating, update unit status
            if ($data['status'] === 'active') {
                $this->db->update('units', ['status'=>'occupied','updated_at'=>date('Y-m-d H:i:s')], 'id=?', [$data['unit_id']]);
            }
            Helper::setFlash('success', 'Lease created: '.$leaseNum);
            $this->redirect(APP_URL . '/admin/leases/'.$id);
        } catch (\Exception $e) {
            Helper::setFlash('danger', 'Error: '.$e->getMessage());
            $this->back();
        }
    }

    public function show(string $id): void
    {
        $lease = $this->db->fetch(
            "SELECT l.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, t.phone, t.national_id,
                    u.unit_number, u.unit_type, u.bedrooms, u.bathrooms, u.floor_size,
                    p.name AS property_name, p.address,
                    CONCAT(cb.first_name,' ',cb.last_name) AS created_by_name
             FROM leases l
             JOIN tenants t ON t.id=l.tenant_id
             JOIN units u ON u.id=l.unit_id
             JOIN properties p ON p.id=l.property_id
             LEFT JOIN users cb ON cb.id=l.created_by
             WHERE l.id=?", [$id]
        );
        if (!$lease) { $this->abort(404); return; }
        $invoices = $this->db->fetchAll("SELECT * FROM invoices WHERE lease_id=? ORDER BY period_from DESC", [$id]);
        $payments = $this->db->fetchAll("SELECT pay.*, pm.name AS method_name FROM payments pay LEFT JOIN payment_methods pm ON pm.id=pay.payment_method_id WHERE pay.lease_id=? ORDER BY pay.payment_date DESC", [$id]);
        $this->adminView('lease.show', compact('lease','invoices','payments') + ['title'=>'Lease '.$lease['lease_number']]);
    }

    public function edit(string $id): void
    {
        $lease   = $this->db->fetch("SELECT * FROM leases WHERE id=?", [$id]);
        if (!$lease) { $this->abort(404); return; }
        $tenants    = $this->db->fetchAll("SELECT id, CONCAT(tenant_code,' - ',first_name,' ',last_name) AS name FROM tenants WHERE status='active' ORDER BY first_name");
        $units      = $this->db->fetchAll("SELECT u.id, CONCAT(p.name,' - Unit ',u.unit_number) AS name, u.monthly_rent, u.security_deposit FROM units u JOIN properties p ON p.id=u.property_id ORDER BY p.name,u.unit_number");
        $properties = $this->db->fetchAll("SELECT id,name FROM properties WHERE status='active' ORDER BY name");
        $this->adminView('lease.form', compact('lease','tenants','units','properties') + ['title'=>'Edit Lease']);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $oldLease = $this->db->fetch("SELECT status, unit_id FROM leases WHERE id=?", [$id]);
        $data = [
            'status'           => $this->input('status','pending'),
            'monthly_rent'     => (float)$this->input('monthly_rent',0),
            'end_date'         => $this->input('end_date'),
            'grace_period_days'=> (int)$this->input('grace_period_days',7),
            'late_fee_percent' => (float)$this->input('late_fee_percent',0),
            'discount_amount'  => (float)$this->input('discount_amount',0),
            'terms_conditions' => $this->input('terms_conditions','') ?: null,
            'updated_at'       => date('Y-m-d H:i:s'),
        ];
        if ($data['status'] === 'terminated') {
            $data['terminated_at']     = date('Y-m-d H:i:s');
            $data['termination_reason']= $this->input('termination_reason','') ?: null;
        }
        $this->db->update('leases', $data, 'id=?', [$id]);
        Helper::setFlash('success', 'Lease updated.');
        $this->redirect(APP_URL . '/admin/leases/'.$id);
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('leases', ['status'=>'terminated','updated_at'=>date('Y-m-d H:i:s')], 'id=?', [$id]);
        Helper::setFlash('success', 'Lease terminated.');
        $this->redirect(APP_URL . '/admin/leases');
    }

    public function pdf(string $id): void
    {
        $lease = $this->db->fetch(
            "SELECT l.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, t.phone, t.national_id, t.address AS tenant_address,
                    u.unit_number, u.unit_type, u.bedrooms, u.bathrooms, u.floor_size,
                    p.name AS property_name, p.address AS property_address
             FROM leases l JOIN tenants t ON t.id=l.tenant_id JOIN units u ON u.id=l.unit_id JOIN properties p ON p.id=l.property_id WHERE l.id=?", [$id]
        );
        if (!$lease) { $this->abort(404); return; }
        $settings = array_column($this->db->fetchAll("SELECT `key`,`value` FROM settings"), 'value','key');
        // Generate simple HTML PDF using inline CSS
        header('Content-Type: text/html; charset=utf-8');
        $this->adminView('lease.pdf', compact('lease','settings') + ['title'=>'Lease Contract'], '');
    }
}
