<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class MaintenanceController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager']);
    }

    public function index(): void
    {
        $priority = $_GET['priority'] ?? '';
        $status   = $_GET['status']   ?? '';
        $conditions = ['1=1']; $params = [];
        if ($priority) { $conditions[] = 'mr.priority=?'; $params[] = $priority; }
        if ($status)   { $conditions[] = 'mr.status=?';   $params[] = $status; }
        $where = implode(' AND ', $conditions);
        $requests = $this->db->fetchAll(
            "SELECT mr.*, u.unit_number, p.name AS property_name,
                    CONCAT(t.first_name,' ',t.last_name) AS tenant_name
             FROM maintenance_requests mr
             JOIN units u ON u.id=mr.unit_id
             JOIN properties p ON p.id=mr.property_id
             LEFT JOIN tenants t ON t.id=mr.tenant_id
             WHERE $where ORDER BY FIELD(mr.priority,'emergency','high','medium','low'), mr.created_at DESC",
            $params
        );
        $stats = [
            'open'        => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE status='open'"),
            'in_progress' => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE status='in_progress'"),
            'completed'   => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE status='completed'"),
            'emergency'   => (int)$this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE priority='emergency' AND status NOT IN ('completed','cancelled')"),
        ];
        $this->adminView('maintenance.index', compact('requests','stats','priority','status') + ['title'=>'Maintenance Requests']);
    }

    public function show(string $id): void
    {
        $request = $this->db->fetch(
            "SELECT mr.*, u.unit_number, p.name AS property_name,
                    CONCAT(t.first_name,' ',t.last_name) AS tenant_name, t.phone AS tenant_phone,
                    CONCAT(a.first_name,' ',a.last_name) AS assigned_to_name
             FROM maintenance_requests mr
             JOIN units u ON u.id=mr.unit_id
             JOIN properties p ON p.id=mr.property_id
             LEFT JOIN tenants t ON t.id=mr.tenant_id
             LEFT JOIN users a ON a.id=mr.assigned_to
             WHERE mr.id=?", [$id]
        );
        if (!$request) { $this->abort(404); return; }
        $staff = $this->db->fetchAll("SELECT id, CONCAT(first_name,' ',last_name) AS name FROM users WHERE role_id IN (1,3) ORDER BY first_name");
        $this->adminView('maintenance.show', compact('request','staff') + ['title'=>'Maintenance #'.$request['request_number']]);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $data = [
            'status'          => $this->input('status','open'),
            'assigned_to'     => $this->input('assigned_to') ?: null,
            'technician_name' => Helper::sanitize($this->input('technician_name','')),
            'estimated_cost'  => (float)$this->input('estimated_cost',0),
            'actual_cost'     => (float)$this->input('actual_cost',0),
            'materials_cost'  => (float)$this->input('materials_cost',0),
            'notes'           => $this->input('notes','') ?: null,
            'updated_at'      => date('Y-m-d H:i:s'),
        ];
        if ($data['status'] === 'in_progress') $data['started_at'] = date('Y-m-d H:i:s');
        if ($data['status'] === 'completed')   $data['completed_at'] = date('Y-m-d H:i:s');
        $this->db->update('maintenance_requests', $data, 'id=?', [$id]);
        Helper::setFlash('success', 'Maintenance request updated.');
        $this->redirect(APP_URL . '/admin/maintenance/' . $id);
    }
}
