<?php
namespace App\Controllers;

class Helpdesk extends BaseController
{
    public function index()
    {
        $filterStatus = $this->request->getGet('status') ?? '';
        $q = $this->db->table('maintenance_requests r')
            ->select('r.*, f.name as facility_name')
            ->join('facilities f', 'f.id=r.facility_id', 'left');
        $this->scopeFacilities($q, 'r.facility_id');
        if ($filterStatus) {
            $q->where('r.status', $filterStatus);
        }
        $pg          = $this->paginate(25);
        $total       = (clone $q)->countAllResults(false);
        $requests    = $q->orderBy('CASE r.priority WHEN \'critical\' THEN 1 WHEN \'high\' THEN 2 WHEN \'medium\' THEN 3 ELSE 4 END', '')
            ->orderBy('r.created_at', 'DESC')
            ->limit($pg['perPage'], $pg['offset'])
            ->get()
            ->getResultArray();

        $kpi = [
            'pending'   => $this->countScopedMaintenanceRequests('pending'),
            'reviewed'  => $this->countScopedMaintenanceRequests('reviewed'),
            'converted' => $this->countScopedMaintenanceRequests('converted'),
            'rejected'  => $this->countScopedMaintenanceRequests('rejected'),
        ];

        return view('helpdesk/index', $this->viewData([
            'title'        => 'Help Desk',
            'requests'     => $requests,
            'filterStatus' => $filterStatus,
            'kpi'          => $kpi,
            'totalCount'   => $total,
            'perPage'      => $pg['perPage'],
            'currentPage'  => $pg['page'],
        ]));
    }

    public function view(int $id)
    {
        $req = $this->db->table('maintenance_requests r')
            ->select('r.*, f.name as facility_name, ru.name as reviewed_by_name')
            ->join('facilities f', 'f.id=r.facility_id', 'left')
            ->join('users ru', 'ru.id=r.reviewed_by', 'left')
            ->where('r.id', $id)
            ->get()
            ->getRowArray();
        if (!$req) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $workOrder   = $req['converted_to_wo']
            ? $this->db->table('work_orders')->where('id', $req['converted_to_wo'])->get()->getRowArray()
            : null;
        $facilities  = $this->db->table('facilities')->where('status', 'active')->get()->getResultArray();
        $technicians = $this->usersByRole('technician');
        $canManage   = in_array(session()->get('user_role'), ['super_admin', 'facility_manager', 'property_manager', 'supervisor'], true);

        return view('helpdesk/view', $this->viewData([
            'title'       => $req['ticket_number'],
            'req'         => $req,
            'workOrder'   => $workOrder,
            'facilities'  => $facilities,
            'technicians' => $technicians,
            'canManage'   => $canManage,
        ]));
    }

    /** Property manager verification: pending → reviewed */
    public function verify(int $id)
    {
        $this->requireRole('super_admin', 'facility_manager', 'property_manager', 'supervisor');
        $req = $this->db->table('maintenance_requests')->where('id', $id)->get()->getRowArray();
        if (!$req || $req['status'] !== 'pending') {
            return redirect()->back()->with('error', 'Only pending tickets can be verified.');
        }

        $this->db->table('maintenance_requests')->where('id', $id)->update([
            'status'      => 'reviewed',
            'reviewed_by' => session()->get('user_id'),
            'reviewed_at' => date('Y-m-d H:i:s'),
        ]);
        $this->logActivity('verify', 'helpdesk', $id, 'Ticket verified');

        return redirect()->to(base_url('helpdesk/view/' . $id))->with('success', 'Ticket verified. Ready for work order conversion.');
    }

    /** Reject enquiry: pending/reviewed → rejected */
    public function reject(int $id)
    {
        $this->requireRole('super_admin', 'facility_manager', 'property_manager', 'supervisor');
        $req = $this->db->table('maintenance_requests')->where('id', $id)->get()->getRowArray();
        if (!$req || !in_array($req['status'], ['pending', 'reviewed'], true)) {
            return redirect()->back()->with('error', 'This ticket cannot be rejected.');
        }

        $notes = esc($this->request->getPost('reject_reason') ?? '');
        $this->db->table('maintenance_requests')->where('id', $id)->update([
            'status'      => 'rejected',
            'reviewed_by' => session()->get('user_id'),
            'reviewed_at' => date('Y-m-d H:i:s'),
        ]);
        $this->logActivity('reject', 'helpdesk', $id, $notes ?: 'Ticket rejected');

        return redirect()->to(base_url('helpdesk'))->with('success', 'Ticket rejected.');
    }

    public function convert(int $id)
    {
        $this->requireRole('super_admin', 'facility_manager', 'property_manager', 'supervisor');
        $req = $this->db->table('maintenance_requests')->where('id', $id)->get()->getRowArray();
        if (!$req) {
            return redirect()->back()->with('error', 'Request not found.');
        }
        if (!in_array($req['status'], ['reviewed', 'pending'], true)) {
            return redirect()->back()->with('error', 'Only verified or pending tickets can be converted.');
        }

        $facilityId = $this->request->getPost('facility_id') ?: $req['facility_id'];
        $priority   = $this->request->getPost('priority') ?? $req['priority'];
        $assignedTo = $this->request->getPost('assigned_to') ?: null;
        $slaRule    = $this->db->table('sla_rules')->where('priority', $priority)->get()->getRowArray();
        $slaDue     = $slaRule ? date('Y-m-d H:i:s', strtotime("+{$slaRule['resolution_hours']} hours")) : null;
        $woNumber   = $this->generateNumber('WO', 'work_orders', 'wo_number');

        $this->db->table('work_orders')->insert([
            'wo_number'     => $woNumber,
            'facility_id'   => $facilityId,
            'title'         => 'Maintenance: ' . substr($req['description'], 0, 80),
            'description'   => $req['description'],
            'type'          => 'corrective',
            'priority'      => $priority,
            'status'        => $assignedTo ? 'assigned' : 'new',
            'assigned_to'   => $assignedTo,
            'created_by'    => session()->get('user_id'),
            'sla_due'       => $slaDue,
            'requester_name'=> $req['requester_name'],
            'requester_email'=> $req['requester_email'],
            'requester_phone'=> $req['requester_phone'],
        ]);
        $woId = $this->db->insertID();

        $this->db->table('maintenance_requests')->where('id', $id)->update([
            'status'          => 'converted',
            'converted_to_wo' => $woId,
            'reviewed_by'     => session()->get('user_id'),
            'reviewed_at'     => date('Y-m-d H:i:s'),
        ]);
        $this->logActivity('convert', 'helpdesk', $id, "Converted to $woNumber");

        return redirect()->to(base_url('workorders/view/' . $woId))->with('success', "Request converted to Work Order $woNumber.");
    }

    public function updateStatus(int $id)
    {
        $this->requireRole('super_admin', 'facility_manager', 'property_manager', 'supervisor');
        $status = $this->request->getPost('status');
        if (!in_array($status, ['pending', 'reviewed', 'rejected'], true)) {
            return redirect()->back()->with('error', 'Invalid status.');
        }

        $this->db->table('maintenance_requests')->where('id', $id)->update([
            'status'      => $status,
            'reviewed_by' => session()->get('user_id'),
            'reviewed_at' => date('Y-m-d H:i:s'),
        ]);
        $this->logActivity('status_change', 'helpdesk', $id, "Status → $status");

        return redirect()->to(base_url('helpdesk/view/' . $id))->with('success', 'Status updated.');
    }

    public function submitFeedback(int $id)
    {
        $rating  = (int) $this->request->getPost('rating');
        $comment = esc($this->request->getPost('comment'));
        if ($rating < 1 || $rating > 5) {
            return redirect()->back()->with('error', 'Invalid rating');
        }

        $exists = $this->db->table('helpdesk_feedback')->where('request_id', $id)->countAllResults();
        if ($exists) {
            $this->db->table('helpdesk_feedback')->where('request_id', $id)->update(['rating' => $rating, 'comment' => $comment]);
        } else {
            $this->db->table('helpdesk_feedback')->insert(['request_id' => $id, 'rating' => $rating, 'comment' => $comment]);
        }

        return redirect()->to(base_url('helpdesk/view/' . $id))->with('success', 'Feedback submitted. Thank you!');
    }
}
