<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AcademicPeriodModel;
use App\Models\CounselingTicketModel;
use App\Models\TeacherModel;

class Counseling extends BaseController
{
    protected $periodModel;
    protected $ticketModel;
    protected $teacherModel;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        $this->periodModel  = new AcademicPeriodModel();
        $this->ticketModel  = new CounselingTicketModel();
        $this->teacherModel = new TeacherModel();
    }

    private function checkAccess()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin', 'kamad'])) {
            return redirect()->to('/dashboard');
        }
        return true;
    }

    public function index()
    {
        $access = $this->checkAccess();
        if ($access instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $access;
        }

        $activePeriod = $this->periodModel->getActive();
        $selectedPeriodId = $this->request->getGet('period_id') ?: ($activePeriod ? $activePeriod['id'] : null);
        $periods = $this->periodModel->getAllWithYear();

        // Filters
        $typeFilter     = $this->request->getGet('type');
        $statusFilter   = $this->request->getGet('status');
        $categoryFilter = $this->request->getGet('category');

        // Fetch tickets with student & teacher details
        $query = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, classrooms.name as classroom_name, teachers.name as teacher_name')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->join('student_academic_histories', 'student_academic_histories.student_id = students.id AND student_academic_histories.academic_period_id = counseling_tickets.academic_period_id', 'left')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id', 'left')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id');

        if ($selectedPeriodId) {
            $query->where('counseling_tickets.academic_period_id', $selectedPeriodId);
        }
        if ($typeFilter) {
            $query->where('counseling_tickets.type', $typeFilter);
        }
        if ($statusFilter) {
            $query->where('counseling_tickets.status', $statusFilter);
        }
        if ($categoryFilter) {
            $query->where('counseling_tickets.category', $categoryFilter);
        }

        $tickets = $query->orderBy('counseling_tickets.created_at', 'DESC')->findAll();

        // Statistics calculation (for dashboard badges)
        $stats = [
            'total'      => 0,
            'open'       => 0,
            'closed'     => 0,
            'pengaduan'  => 0,
            'konseling'  => 0,
            'anonymous'  => 0,
        ];

        $statsQuery = $this->ticketModel;
        if ($selectedPeriodId) {
            $statsQuery = $statsQuery->where('academic_period_id', $selectedPeriodId);
        }
        $allPeriodTickets = $statsQuery->findAll();

        foreach ($allPeriodTickets as $t) {
            $stats['total']++;
            if ($t['status'] === 'open') $stats['open']++;
            if ($t['status'] === 'closed') $stats['closed']++;
            if ($t['type'] === 'pengaduan') $stats['pengaduan']++;
            if ($t['type'] === 'konseling') $stats['konseling']++;
            if ((int)$t['is_anonymous'] === 1) $stats['anonymous']++;
        }

        // Hitung KPI Laporan Eksekutif
        $responseTimes = [];
        if ($selectedPeriodId) {
            $db = \Config\Database::connect();
            $ticketsWithReplies = $db->table('counseling_tickets t')
                ->select('t.id, t.created_at as ticket_created, MIN(m.created_at) as first_reply')
                ->join('counseling_messages m', 'm.ticket_id = t.id')
                ->where('m.sender_role', 'teacher')
                ->where('t.academic_period_id', $selectedPeriodId)
                ->groupBy('t.id')
                ->get()
                ->getResultArray();
                
            foreach ($ticketsWithReplies as $row) {
                $created = new \DateTime($row['ticket_created']);
                $replied = new \DateTime($row['first_reply']);
                $diffSeconds = $replied->getTimestamp() - $created->getTimestamp();
                if ($diffSeconds > 0) {
                    $responseTimes[] = $diffSeconds;
                }
            }
        }
        
        $avgResponseHours = 0;
        if (count($responseTimes) > 0) {
            $avgResponseHours = round((array_sum($responseTimes) / count($responseTimes)) / 3600, 1);
        }
        $resolutionRate = $stats['total'] > 0 ? round(($stats['closed'] / $stats['total']) * 100) : 0;

        return view('admin/counseling/index', [
            'title'            => 'Rekap Pengaduan & E-Konseling',
            'tickets'          => $tickets,
            'periods'          => $periods,
            'selectedPeriodId' => $selectedPeriodId,
            'typeFilter'       => $typeFilter,
            'statusFilter'     => $statusFilter,
            'categoryFilter'   => $categoryFilter,
            'stats'            => $stats,
            'avgResponseHours' => $avgResponseHours,
            'resolutionRate'   => $resolutionRate
        ]);
    }

    public function exportRecap()
    {
        $access = $this->checkAccess();
        if ($access instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $access;
        }

        $selectedPeriodId = $this->request->getGet('period_id');
        $activePeriod = $this->periodModel->getActive();
        $period = null;
        if ($selectedPeriodId) {
            $period = $this->periodModel->select('academic_periods.*, academic_years.name as year_name')
                ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
                ->find($selectedPeriodId);
        } else {
            $period = $activePeriod;
        }

        $typeFilter     = $this->request->getGet('type');
        $statusFilter   = $this->request->getGet('status');
        $categoryFilter = $this->request->getGet('category');

        $query = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, classrooms.name as classroom_name, teachers.name as teacher_name')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->join('student_academic_histories', 'student_academic_histories.student_id = students.id AND student_academic_histories.academic_period_id = counseling_tickets.academic_period_id', 'left')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id', 'left')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id');

        if ($period) {
            $query->where('counseling_tickets.academic_period_id', $period['id']);
        }
        if ($typeFilter) {
            $query->where('counseling_tickets.type', $typeFilter);
        }
        if ($statusFilter) {
            $query->where('counseling_tickets.status', $statusFilter);
        }
        if ($categoryFilter) {
            $query->where('counseling_tickets.category', $categoryFilter);
        }

        $tickets = $query->orderBy('counseling_tickets.created_at', 'ASC')->findAll();

        $settingsModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $settingsModel->getSettings();

        return view('admin/counseling/export_recap', [
            'period'         => $period,
            'tickets'        => $tickets,
            'type'           => $typeFilter,
            'status'         => $statusFilter,
            'category'       => $categoryFilter,
            'schoolSettings' => $schoolSettings
        ]);
    }

    public function detail($id)
    {
        $access = $this->checkAccess();
        if ($access instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $this->response->setJSON(['success' => false, 'message' => 'Akses ditolak.']);
        }

        $ticket = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, classrooms.name as classroom_name, teachers.name as teacher_name')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->join('student_academic_histories', 'student_academic_histories.student_id = students.id AND student_academic_histories.academic_period_id = counseling_tickets.academic_period_id', 'left')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id', 'left')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id')
            ->find($id);

        if (!$ticket) {
            return $this->response->setJSON(['success' => false, 'message' => 'Tiket tidak ditemukan.']);
        }

        return $this->response->setJSON([
            'success' => true,
            'ticket' => $ticket
        ]);
    }
}
