<?php
class PropertyController {

    private function cid() { return Auth::user()['company_id']; }

    public function index() {
        $db = Database::getInstance();
        $cid = $this->cid();

        $search = trim($_GET['search'] ?? '');
        $type = $_GET['type'] ?? '';
        $status = $_GET['status'] ?? '';
        $perPage = 15;
        $currentPage = max(1, (int)($_GET['pg'] ?? 1));
        $offset = ($currentPage - 1) * $perPage;

        $where = "p.company_id = ? AND p.deleted_at IS NULL";
        $params = [$cid];

        if ($search) { $where .= " AND (p.name LIKE ? OR p.address LIKE ? OR p.city LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }
        if ($type) { $where .= " AND p.type = ?"; $params[] = $type; }

        $total = $db->fetchColumn("SELECT COUNT(*) FROM properties p WHERE $where", $params);
        $properties = $db->fetchAll(
            "SELECT p.*, o.first_name as owner_first, o.last_name as owner_last,
                (SELECT COUNT(*) FROM units u WHERE u.property_id = p.id AND u.deleted_at IS NULL) as unit_count,
                (SELECT COUNT(*) FROM units u WHERE u.property_id = p.id AND u.status = 'occupied' AND u.deleted_at IS NULL) as occupied_count
             FROM properties p
             LEFT JOIN owners o ON p.owner_id = o.id
             WHERE $where
             ORDER BY p.created_at DESC LIMIT $perPage OFFSET $offset",
            $params
        );

        $pagination = paginate($total, $perPage, $currentPage, '?page=properties' . ($search ? "&search=$search" : '') . ($type ? "&type=$type" : ''));

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

    public function show() {
        $db = Database::getInstance();
        $id = (int)($_GET['id'] ?? 0);
        $property = $db->fetch(
            "SELECT p.*, o.first_name as owner_first, o.last_name as owner_last, o.email as owner_email
             FROM properties p LEFT JOIN owners o ON p.owner_id = o.id
             WHERE p.id = ? AND p.company_id = ? AND p.deleted_at IS NULL",
            [$id, $this->cid()]
        );
        if (!$property) { flash('error', 'Property not found.'); redirect('?page=properties'); }

        $units = $db->fetchAll("SELECT u.*, t.first_name, t.last_name FROM units u LEFT JOIN tenants t ON u.tenant_id = t.id WHERE u.property_id = ? AND u.deleted_at IS NULL ORDER BY u.unit_number", [$id]);

        $pageTitle = $property['name'];
        $page = 'properties';
        ob_start();
        require APP_PATH . '/views/properties/show.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }

    public function create() {
        $db = Database::getInstance();
        $owners = $db->fetchAll("SELECT id, first_name, last_name FROM owners WHERE company_id = ? AND deleted_at IS NULL ORDER BY first_name", [$this->cid()]);
        $managers = $db->fetchAll("SELECT id, first_name, last_name FROM users WHERE company_id = ? AND deleted_at IS NULL AND status = 'active' ORDER BY first_name", [$this->cid()]);

        $pageTitle = 'Add Property';
        $page = 'properties';
        $property = [];
        ob_start();
        require APP_PATH . '/views/properties/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('name')->required('type')->required('address')->required('city')->required('state')->required('zip');
        if ($v->fails()) { flash('error', $v->firstError()); $_SESSION['_old_input'] = $data; redirect('?page=properties&action=create'); }

        $id = $db->insert('properties', [
            'company_id' => $this->cid(),
            'name' => $data['name'],
            'type' => $data['type'],
            'address' => $data['address'],
            'city' => $data['city'],
            'state' => $data['state'],
            'zip' => $data['zip'],
            'country' => $data['country'] ?? 'US',
            'owner_id' => $data['owner_id'] ?: null,
            'manager_id' => $data['manager_id'] ?: null,
            'notes' => $data['notes'] ?? '',
            'status' => 'active',
        ]);

        auditLog('created', 'properties', $id, null, $data);
        flash('success', 'Property created successfully.');
        redirect("?page=properties&action=show&id=$id");
    }

    public function edit() {
        $db = Database::getInstance();
        $id = (int)($_GET['id'] ?? 0);
        $property = $db->fetch("SELECT * FROM properties WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$property) { flash('error', 'Property not found.'); redirect('?page=properties'); }

        $owners = $db->fetchAll("SELECT id, first_name, last_name FROM owners WHERE company_id = ? AND deleted_at IS NULL ORDER BY first_name", [$this->cid()]);
        $managers = $db->fetchAll("SELECT id, first_name, last_name FROM users WHERE company_id = ? AND deleted_at IS NULL AND status = 'active' ORDER BY first_name", [$this->cid()]);

        $pageTitle = 'Edit Property';
        $page = 'properties';
        ob_start();
        require APP_PATH . '/views/properties/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);
        $property = $db->fetch("SELECT * FROM properties WHERE id = ? AND company_id = ? AND deleted_at IS NULL", [$id, $this->cid()]);
        if (!$property) { flash('error', 'Property not found.'); redirect('?page=properties'); }

        $data = $_POST;
        $v = new Validator($data);
        $v->required('name')->required('type')->required('address')->required('city')->required('state')->required('zip');
        if ($v->fails()) { flash('error', $v->firstError()); $_SESSION['_old_input'] = $data; redirect("?page=properties&action=edit&id=$id"); }

        $db->update('properties', [
            'name' => $data['name'],
            'type' => $data['type'],
            'address' => $data['address'],
            'city' => $data['city'],
            'state' => $data['state'],
            'zip' => $data['zip'],
            'country' => $data['country'] ?? 'US',
            'owner_id' => $data['owner_id'] ?: null,
            'manager_id' => $data['manager_id'] ?: null,
            'notes' => $data['notes'] ?? '',
        ], 'id = ?', [$id]);

        auditLog('updated', 'properties', $id, $property, $data);
        flash('success', 'Property updated successfully.');
        redirect("?page=properties&action=show&id=$id");
    }

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