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

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

        $where = "u.company_id = ? AND u.deleted_at IS NULL";
        $params = [$cid];
        if ($search) { $where .= " AND (u.unit_number LIKE ? OR p.name LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
        if ($status) { $where .= " AND u.status = ?"; $params[] = $status; }
        if ($property_id) { $where .= " AND u.property_id = ?"; $params[] = $property_id; }

        $total = $db->fetchColumn("SELECT COUNT(*) FROM units u LEFT JOIN properties p ON u.property_id = p.id WHERE $where", $params);
        $units = $db->fetchAll(
            "SELECT u.*, p.name as property_name, t.first_name, t.last_name
             FROM units u LEFT JOIN properties p ON u.property_id = p.id LEFT JOIN tenants t ON u.tenant_id = t.id
             WHERE $where ORDER BY p.name, u.unit_number LIMIT $perPage OFFSET $offset", $params
        );
        $properties = $db->fetchAll("SELECT id, name FROM properties WHERE company_id = ? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $pagination = paginate($total, $perPage, $currentPage, '?page=units' . ($search ? "&search=$search" : '') . ($status ? "&status=$status" : '') . ($property_id ? "&property_id=$property_id" : ''));

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

    public function show() {
        $db = Database::getInstance();
        $id = (int)($_GET['id'] ?? 0);
        $unit = $db->fetch(
            "SELECT u.*, p.name as property_name, t.first_name, t.last_name, t.email as tenant_email, t.phone as tenant_phone
             FROM units u LEFT JOIN properties p ON u.property_id = p.id LEFT JOIN tenants t ON u.tenant_id = t.id
             WHERE u.id = ? AND u.company_id = ? AND u.deleted_at IS NULL", [$id, $this->cid()]
        );
        if (!$unit) { flash('error', 'Unit not found.'); redirect('?page=units'); }
        $lease = $db->fetch("SELECT * FROM leases WHERE unit_id = ? AND status = 'active' AND deleted_at IS NULL ORDER BY start_date DESC LIMIT 1", [$id]);

        $pageTitle = 'Unit #' . $unit['unit_number']; $page = 'units';
        ob_start(); require APP_PATH . '/views/units/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()]);
        $unit = ['property_id' => $_GET['property_id'] ?? ''];
        $pageTitle = 'Add Unit'; $page = 'units';
        ob_start(); require APP_PATH . '/views/units/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('unit_number')->required('property_id');
        if ($v->fails()) { flash('error', $v->firstError()); $_SESSION['_old_input'] = $data; redirect('?page=units&action=create'); }

        $id = $db->insert('units', [
            'company_id' => $this->cid(), 'property_id' => $data['property_id'], 'unit_number' => $data['unit_number'],
            'type' => $data['type'] ?? '', 'bedrooms' => $data['bedrooms'] ?: null, 'bathrooms' => $data['bathrooms'] ?: null,
            'sqft' => $data['sqft'] ?: null, 'market_rent' => $data['market_rent'] ?: null, 'deposit_amount' => $data['deposit_amount'] ?: null,
            'status' => $data['status'] ?? 'vacant', 'notes' => $data['notes'] ?? '',
        ]);
        auditLog('created', 'units', $id, null, $data);
        flash('success', 'Unit created successfully.');
        redirect("?page=units&action=show&id=$id");
    }

    public function edit() {
        $db = Database::getInstance(); $id = (int)($_GET['id'] ?? 0);
        $unit = $db->fetch("SELECT * FROM units WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$unit) { flash('error', 'Unit not found.'); redirect('?page=units'); }
        $properties = $db->fetchAll("SELECT id, name FROM properties WHERE company_id = ? AND deleted_at IS NULL ORDER BY name", [$this->cid()]);
        $pageTitle = 'Edit Unit'; $page = 'units';
        ob_start(); require APP_PATH . '/views/units/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;
        $unit = $db->fetch("SELECT * FROM units WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$unit) { flash('error', 'Unit not found.'); redirect('?page=units'); }
        $v = new Validator($data); $v->required('unit_number')->required('property_id');
        if ($v->fails()) { flash('error', $v->firstError()); redirect("?page=units&action=edit&id=$id"); }

        $db->update('units', [
            'property_id' => $data['property_id'], 'unit_number' => $data['unit_number'], 'type' => $data['type'] ?? '',
            'bedrooms' => $data['bedrooms'] ?: null, 'bathrooms' => $data['bathrooms'] ?: null, 'sqft' => $data['sqft'] ?: null,
            'market_rent' => $data['market_rent'] ?: null, 'deposit_amount' => $data['deposit_amount'] ?: null,
            'status' => $data['status'] ?? 'vacant', 'notes' => $data['notes'] ?? '',
        ], 'id = ?', [$id]);
        auditLog('updated', 'units', $id, $unit, $data);
        flash('success', 'Unit updated.'); redirect("?page=units&action=show&id=$id");
    }

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