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

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

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

        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests m LEFT JOIN tenants t ON m.tenant_id=t.id $where", $params);
        $offset = ($page - 1) * $perPage;
        $requests = $this->db->fetchAll("SELECT m.*, t.first_name, t.last_name, p.name as property_name, u.unit_number FROM maintenance_requests m LEFT JOIN tenants t ON m.tenant_id=t.id LEFT JOIN properties p ON m.property_id=p.id LEFT JOIN units u ON m.unit_id=u.id $where ORDER BY FIELD(m.priority,'emergency','high','medium','low'), m.created_at DESC LIMIT $perPage OFFSET $offset", $params);

        $openCount = $this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE company_id=? AND status NOT IN ('completed','closed','cancelled') AND deleted_at IS NULL", [$cid]);
        $pagination = paginationHtml($total, $page, $perPage, '?page=maintenance');
        require 'app/views/maintenance/index.php';
    }

    public function create() {
        $request = 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", [$cid]);
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        require 'app/views/maintenance/form.php';
    }

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

        $this->db->insert('maintenance_requests', [
            'company_id' => Auth::user()['company_id'], 'property_id' => $_POST['property_id'],
            'unit_id' => $_POST['unit_id'] ?: null, 'tenant_id' => $_POST['tenant_id'] ?: null,
            'title' => $_POST['title'], 'description' => $_POST['description'] ?? null,
            'category' => $_POST['category'] ?? null, 'priority' => $_POST['priority'] ?? 'medium',
            'status' => $_POST['status'] ?? 'new', 'assigned_vendor_id' => $_POST['assigned_vendor_id'] ?: null,
            'permission_to_enter' => isset($_POST['permission_to_enter']) ? 1 : 0,
        ]);
        flash('success', 'Maintenance request created.');
        redirect('?page=maintenance');
    }

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

        $workOrders = $this->db->fetchAll("SELECT w.*, v.company_name as vendor_name FROM work_orders w LEFT JOIN vendors v ON w.vendor_id=v.id WHERE w.maintenance_request_id=? AND w.deleted_at IS NULL", [$id]);
        require 'app/views/maintenance/show.php';
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $request = $this->db->fetch("SELECT * FROM maintenance_requests WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$request) { flash('error', 'Request not found.'); redirect('?page=maintenance'); }
        $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", [$cid]);
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        require 'app/views/maintenance/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('maintenance_requests', [
            'property_id' => $_POST['property_id'], 'unit_id' => $_POST['unit_id'] ?: null,
            'tenant_id' => $_POST['tenant_id'] ?: null, 'title' => $_POST['title'],
            'description' => $_POST['description'] ?? null, 'category' => $_POST['category'] ?? null,
            'priority' => $_POST['priority'] ?? 'medium', 'status' => $_POST['status'] ?? 'new',
            'assigned_vendor_id' => $_POST['assigned_vendor_id'] ?: null,
            'permission_to_enter' => isset($_POST['permission_to_enter']) ? 1 : 0,
            'estimated_cost' => $_POST['estimated_cost'] ?: null, 'actual_cost' => $_POST['actual_cost'] ?: null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Request updated.');
        redirect('?page=maintenance');
    }

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