<?php
class LeaseController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? '';
        $status = $_GET['status'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1));
        $perPage = ITEMS_PER_PAGE;
        $cid = Auth::user()['company_id'];

        $where = "WHERE l.deleted_at IS NULL AND l.company_id = ?";
        $params = [$cid];
        if ($search) { $where .= " AND (t.first_name LIKE ? OR t.last_name LIKE ? OR p.name LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
        if ($status) { $where .= " AND l.status = ?"; $params[] = $status; }

        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM leases l LEFT JOIN tenants t ON l.tenant_id=t.id LEFT JOIN properties p ON l.property_id=p.id $where", $params);
        $offset = ($page - 1) * $perPage;
        $leases = $this->db->fetchAll("SELECT l.*, t.first_name, t.last_name, p.name as property_name, u.unit_number FROM leases l LEFT JOIN tenants t ON l.tenant_id=t.id LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id $where ORDER BY l.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $pagination = paginationHtml($total, $page, $perPage, '?page=leases');
        require 'app/views/leases/index.php';
    }

    public function create() {
        $lease = null;
        $cid = Auth::user()['company_id'];
        $tenants = $this->db->fetchAll("SELECT id, first_name, last_name FROM tenants WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $units = $this->db->fetchAll("SELECT u.id, u.unit_number, p.name as property_name FROM units u JOIN properties p ON u.property_id=p.id WHERE u.company_id=? AND u.deleted_at IS NULL ORDER BY p.name, u.unit_number", [$cid]);
        require 'app/views/leases/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST);
        $v->required('tenant_id')->required('property_id')->required('unit_id')->required('start_date')->required('end_date')->required('rent_amount')->numeric('rent_amount');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=leases&action=create'); }

        $this->db->insert('leases', [
            'company_id' => Auth::user()['company_id'], 'tenant_id' => $_POST['tenant_id'],
            'property_id' => $_POST['property_id'], 'unit_id' => $_POST['unit_id'],
            'start_date' => $_POST['start_date'], 'end_date' => $_POST['end_date'],
            'rent_amount' => $_POST['rent_amount'], 'rent_frequency' => $_POST['rent_frequency'] ?? 'monthly',
            'security_deposit' => $_POST['security_deposit'] ?? 0, 'late_fee_amount' => $_POST['late_fee_amount'] ?? 0,
            'grace_period_days' => $_POST['grace_period_days'] ?? 0, 'status' => $_POST['status'] ?? 'draft',
            'notes' => $_POST['notes'] ?? null,
        ]);

        // Update unit status
        $this->db->update('units', ['status' => 'occupied', 'current_rent' => $_POST['rent_amount']], 'id = ?', [$_POST['unit_id']]);

        flash('success', 'Lease created successfully.');
        redirect('?page=leases');
    }

    public function show($id) {
        $cid = Auth::user()['company_id'];
        $lease = $this->db->fetch("SELECT l.*, t.first_name, t.last_name, t.email as tenant_email, p.name as property_name, u.unit_number FROM leases l LEFT JOIN tenants t ON l.tenant_id=t.id LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id WHERE l.id=? AND l.company_id=? AND l.deleted_at IS NULL", [$id, $cid]);
        if (!$lease) { flash('error', 'Lease not found.'); redirect('?page=leases'); }

        $payments = $this->db->fetchAll("SELECT * FROM payments WHERE lease_id=? AND deleted_at IS NULL ORDER BY payment_date DESC LIMIT 10", [$id]);
        $charges = $this->db->fetchAll("SELECT * FROM charges WHERE lease_id=? AND deleted_at IS NULL ORDER BY due_date DESC LIMIT 10", [$id]);
        require 'app/views/leases/show.php';
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $lease = $this->db->fetch("SELECT * FROM leases WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$lease) { flash('error', 'Lease not found.'); redirect('?page=leases'); }
        $tenants = $this->db->fetchAll("SELECT id, first_name, last_name FROM tenants WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $units = $this->db->fetchAll("SELECT u.id, u.unit_number, p.name as property_name FROM units u JOIN properties p ON u.property_id=p.id WHERE u.company_id=? AND u.deleted_at IS NULL ORDER BY p.name, u.unit_number", [$cid]);
        require 'app/views/leases/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $v = new Validator($_POST);
        $v->required('tenant_id')->required('start_date')->required('end_date')->required('rent_amount')->numeric('rent_amount');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect("?page=leases&action=edit&id=$id"); }

        $this->db->update('leases', [
            'tenant_id' => $_POST['tenant_id'], 'property_id' => $_POST['property_id'],
            'unit_id' => $_POST['unit_id'], 'start_date' => $_POST['start_date'],
            'end_date' => $_POST['end_date'], 'rent_amount' => $_POST['rent_amount'],
            'rent_frequency' => $_POST['rent_frequency'] ?? 'monthly',
            'security_deposit' => $_POST['security_deposit'] ?? 0,
            'late_fee_amount' => $_POST['late_fee_amount'] ?? 0,
            'grace_period_days' => $_POST['grace_period_days'] ?? 0,
            'status' => $_POST['status'] ?? 'active', 'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Lease updated.');
        redirect('?page=leases');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->softDelete('leases', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Lease deleted.');
        redirect('?page=leases');
    }
}
