<?php
class TenantController {
    private function cid() { return Auth::user()['company_id']; }

    public function index() {
        $db = Database::getInstance(); $cid = $this->cid();
        $search = trim($_GET['search'] ?? ''); $status = $_GET['status'] ?? '';
        $perPage = 15; $currentPage = max(1, (int)($_GET['pg'] ?? 1)); $offset = ($currentPage - 1) * $perPage;

        $where = "t.company_id = ? AND t.deleted_at IS NULL"; $params = [$cid];
        if ($search) { $where .= " AND (t.first_name LIKE ? OR t.last_name LIKE ? OR t.email LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }
        if ($status) { $where .= " AND t.status = ?"; $params[] = $status; }

        $total = $db->fetchColumn("SELECT COUNT(*) FROM tenants t WHERE $where", $params);
        $tenants = $db->fetchAll(
            "SELECT t.*, u.unit_number, p.name as property_name,
                (SELECT COALESCE(SUM(c.amount),0) - COALESCE((SELECT SUM(py.amount) FROM payments py WHERE py.tenant_id = t.id AND py.status = 'completed' AND py.deleted_at IS NULL),0) FROM charges c WHERE c.tenant_id = t.id AND c.deleted_at IS NULL) as balance
             FROM tenants t LEFT JOIN units u ON t.unit_id = u.id LEFT JOIN properties p ON t.property_id = p.id
             WHERE $where ORDER BY t.last_name, t.first_name LIMIT $perPage OFFSET $offset", $params
        );
        $pagination = paginate($total, $perPage, $currentPage, '?page=tenants' . ($search ? "&search=$search" : '') . ($status ? "&status=$status" : ''));

        $pageTitle = 'Tenants'; $page = 'tenants';
        ob_start(); require APP_PATH . '/views/tenants/index.php'; $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }

    public function show() {
        $db = Database::getInstance(); $id = (int)($_GET['id'] ?? 0);
        $tenant = $db->fetch(
            "SELECT t.*, u.unit_number, p.name as property_name FROM tenants t LEFT JOIN units u ON t.unit_id = u.id LEFT JOIN properties p ON t.property_id = p.id
             WHERE t.id = ? AND t.company_id = ? AND t.deleted_at IS NULL", [$id, $this->cid()]
        );
        if (!$tenant) { flash('error', 'Tenant not found.'); redirect('?page=tenants'); }

        $lease = $db->fetch("SELECT * FROM leases WHERE tenant_id = ? AND status = 'active' AND deleted_at IS NULL LIMIT 1", [$id]);
        $payments = $db->fetchAll("SELECT * FROM payments WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY payment_date DESC LIMIT 15", [$id]);
        $charges = $db->fetchAll("SELECT * FROM charges WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY due_date DESC LIMIT 15", [$id]);
        $maintenanceRequests = $db->fetchAll("SELECT * FROM maintenance_requests WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 10", [$id]);

        $totalCharges = $db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM charges WHERE tenant_id = ? AND deleted_at IS NULL", [$id]);
        $totalPaid = $db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM payments WHERE tenant_id = ? AND status = 'completed' AND deleted_at IS NULL", [$id]);
        $balance = $totalCharges - $totalPaid;

        $pageTitle = $tenant['first_name'] . ' ' . $tenant['last_name']; $page = 'tenants';
        ob_start(); require APP_PATH . '/views/tenants/show.php'; $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }

    public function create() {
        $db = Database::getInstance();
        $properties = $db->fetchAll("SELECT id, name FROM properties WHERE company_id = ? AND deleted_at IS NULL ORDER BY name", [$this->cid()]);
        $units = $db->fetchAll("SELECT id, unit_number, property_id FROM units WHERE company_id = ? AND status = 'vacant' AND deleted_at IS NULL ORDER BY unit_number", [$this->cid()]);
        $tenant = [];
        $pageTitle = 'Add Tenant'; $page = 'tenants';
        ob_start(); require APP_PATH . '/views/tenants/form.php'; $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }

    public function store() {
        CSRF::verify(); $db = Database::getInstance(); $data = $_POST;
        $v = new Validator($data); $v->required('first_name')->required('last_name')->required('email')->email('email')->unique('email', 'tenants', 'email');
        if ($v->fails()) { flash('error', $v->firstError()); $_SESSION['_old_input'] = $data; redirect('?page=tenants&action=create'); }

        $id = $db->insert('tenants', [
            'company_id' => $this->cid(), 'first_name' => $data['first_name'], 'last_name' => $data['last_name'],
            'email' => $data['email'], 'phone' => $data['phone'] ?? '', 'date_of_birth' => $data['date_of_birth'] ?: null,
            'property_id' => $data['property_id'] ?: null, 'unit_id' => $data['unit_id'] ?: null,
            'emergency_contact' => $data['emergency_contact'] ?? '', 'notes' => $data['notes'] ?? '', 'status' => 'active',
        ]);
        if (!empty($data['unit_id'])) { $db->update('units', ['status' => 'occupied', 'tenant_id' => $id], 'id = ?', [$data['unit_id']]); }
        auditLog('created', 'tenants', $id, null, $data);
        flash('success', 'Tenant created.'); redirect("?page=tenants&action=show&id=$id");
    }

    public function edit() {
        $db = Database::getInstance(); $id = (int)($_GET['id'] ?? 0);
        $tenant = $db->fetch("SELECT * FROM tenants WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$tenant) { flash('error', 'Tenant not found.'); redirect('?page=tenants'); }
        $properties = $db->fetchAll("SELECT id, name FROM properties WHERE company_id = ? AND deleted_at IS NULL ORDER BY name", [$this->cid()]);
        $units = $db->fetchAll("SELECT id, unit_number, property_id FROM units WHERE company_id = ? AND (status = 'vacant' OR id = ?) AND deleted_at IS NULL ORDER BY unit_number", [$this->cid(), $tenant['unit_id'] ?? 0]);
        $pageTitle = 'Edit Tenant'; $page = 'tenants';
        ob_start(); require APP_PATH . '/views/tenants/form.php'; $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }

    public function update() {
        CSRF::verify(); $db = Database::getInstance(); $id = (int)($_POST['id'] ?? 0); $data = $_POST;
        $tenant = $db->fetch("SELECT * FROM tenants WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$tenant) { flash('error', 'Tenant not found.'); redirect('?page=tenants'); }
        $v = new Validator($data); $v->required('first_name')->required('last_name')->required('email')->email('email')->unique('email', 'tenants', 'email', $id);
        if ($v->fails()) { flash('error', $v->firstError()); redirect("?page=tenants&action=edit&id=$id"); }

        $db->update('tenants', [
            'first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email'],
            'phone' => $data['phone'] ?? '', 'date_of_birth' => $data['date_of_birth'] ?: null,
            'property_id' => $data['property_id'] ?: null, 'unit_id' => $data['unit_id'] ?: null,
            'emergency_contact' => $data['emergency_contact'] ?? '', 'notes' => $data['notes'] ?? '',
        ], 'id = ?', [$id]);
        auditLog('updated', 'tenants', $id, $tenant, $data);
        flash('success', 'Tenant updated.'); redirect("?page=tenants&action=show&id=$id");
    }

    public function delete() {
        CSRF::verify(); $db = Database::getInstance(); $id = (int)($_POST['id'] ?? 0);
        $db->softDelete('tenants', 'id = ? AND company_id = ?', [$id, $this->cid()]);
        auditLog('deleted', 'tenants', $id); flash('success', 'Tenant deleted.'); redirect('?page=tenants');
    }
}
