<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Models\Attendance;
use App\Models\Batch;
use App\Models\Student;

class AttendanceController {
    public function index() {
        if (!Auth::hasPermission('attendance')) {
            redirect('/login');
            exit;
        }

        $attendanceModel = new Attendance();
        $batchModel = new Batch();
        
        $date = $_GET['date'] ?? date('Y-m-d');
        $batchId = $_GET['batch_id'] ?? null;
        
        $batches = $batchModel->search();
        
        $selectedBatch = null;
        if ($batchId) {
            $db = \App\Core\Database::getInstance();
            $stmt = $db->prepare("SELECT * FROM batches WHERE id = :id LIMIT 1");
            $stmt->execute(['id' => $batchId]);
            $selectedBatch = $stmt->fetch();
        }

        $students = $attendanceModel->getAttendanceForDate($date, $batchId);
        
        $title = 'Daily Attendance';
        require_once __DIR__ . '/../../views/admin/attendance.php';
    }

    public function save() {
        if (!Auth::hasPermission('attendance')) {
            redirect('/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $attendanceModel = new Attendance();
            $date = $_POST['date'];
            $batchId = $_POST['batch_id'];
            $attendanceData = $_POST['attendance'] ?? [];

            try {
                foreach ($attendanceData as $studentId => $data) {
                    $attendanceModel->save([
                        'student_id' => $studentId,
                        'batch_id' => $batchId,
                        'date' => $date,
                        'in_time' => $data['in_time'] ?? null,
                        'out_time' => $data['out_time'] ?? null,
                        'status' => $data['status'] ?? 'Present',
                        'remarks' => $data['remarks'] ?? null
                    ]);
                }
                $_SESSION['toast'] = ['message' => 'Attendance saved successfully!', 'type' => 'success'];
            } catch (\Exception $e) {
                $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        redirect($_SERVER['HTTP_REFERER']);
        exit;
    }

    public function report() {
        if (!Auth::hasPermission('attendance')) {
            redirect('/login');
            exit;
        }

        $attendanceModel = new Attendance();
        $batchModel = new Batch();
        $studentModel = new Student();

        $params = [
            'batch_id' => $_GET['batch_id'] ?? '',
            'student_id' => $_GET['student_id'] ?? '',
            'from_date' => $_GET['from_date'] ?? date('Y-m-01'),
            'to_date' => $_GET['to_date'] ?? date('Y-m-d'),
        ];

        $report = $attendanceModel->getDetailedReport($params);
        $batches = $batchModel->search();
        $students = $studentModel->search();

        $title = 'Attendance Report';
        require_once __DIR__ . '/../../views/admin/attendance_report.php';
    }

    public function exportPdf() {
        if (!Auth::hasPermission('attendance')) {
            redirect('/login');
            exit;
        }

        $attendanceModel = new Attendance();
        $params = [
            'batch_id' => $_GET['batch_id'] ?? '',
            'student_id' => $_GET['student_id'] ?? '',
            'from_date' => $_GET['from_date'] ?? date('Y-m-01'),
            'to_date' => $_GET['to_date'] ?? date('Y-m-d'),
        ];

        $report = $attendanceModel->getDetailedReport($params);

        // Get Settings
        $db = \App\Core\Database::getInstance();
        $settingsData = $db->query("SELECT * FROM settings")->fetchAll();
        $settings = [];
        foreach ($settingsData as $s) {
            $settings[$s['key_name']] = $s['key_value'];
        }

        $dompdf = new \Dompdf\Dompdf();
        $dompdf->set_option('isRemoteEnabled', true);
        
        ob_start();
        include __DIR__ . '/../../views/admin/attendance_pdf.php';
        $html = ob_get_clean();

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

        $filename = "Attendance-Report-" . date('Y-m-d') . ".pdf";
        $dompdf->stream($filename, ["Attachment" => false]);
        exit;
    }
}
