<?php

namespace App\Controllers;

use App\Core\Auth;
use Dompdf\Dompdf;
use Dompdf\Options;

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

        $title = 'Certificates';
        $db = \App\Core\Database::getInstance();
        
        $search = $_GET['search'] ?? '';
        $query = "SELECT * FROM certificates";
        $params = [];

        if ($search) {
            $query .= " WHERE student_name LIKE ? OR certificate_no LIKE ?";
            $params = ["%$search%", "%$search%"];
        }

        $query .= " ORDER BY created_at DESC";
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $issued_certificates = $stmt->fetchAll();

        require_once __DIR__ . '/../../views/admin/certificates_list.php';
    }

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

        $title = 'Generate Certificate';
        $db = \App\Core\Database::getInstance();
        
        // Fetch courses with duration
        $courses = $db->query("SELECT id, name, duration_months FROM courses WHERE status = 'Active' ORDER BY name ASC")->fetchAll();
        
        // Fetch students joined with admissions to know who belongs to which course
        $students = $db->query("SELECT s.id, s.name, a.course_id 
                                FROM students s 
                                JOIN admissions a ON s.id = a.student_id 
                                WHERE s.status = 'Active' 
                                ORDER BY s.name ASC")->fetchAll();

        // Calculate next sequential ID with CERT- prefix
        $countStmt = $db->query("SELECT COUNT(*) as total FROM certificates");
        $count = $countStmt->fetch()['total'];
        $next_id = 'CERT-' . str_pad($count + 1, 2, '0', STR_PAD_LEFT);

        require_once __DIR__ . '/../../views/admin/certificates_generate.php';
    }

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

        // Handle issuance
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'student_id' => $_POST['student_id'] ?? null,
                'student_name' => $_POST['student_name'] ?? 'N/A',
                'course_name' => $_POST['course_name'] ?? 'N/A',
                'duration' => $_POST['duration'] ?? 'N/A',
                'completion_date' => $_POST['completion_date'] ?? date('Y-m-d'),
                'certificate_no' => $_POST['certificate_no'] ?? 'TMS-' . time()
            ];

            // Log to DB
            $db = \App\Core\Database::getInstance();
            $stmt = $db->prepare("INSERT INTO certificates (student_id, student_name, course_name, duration, certificate_no, issue_date) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $data['student_id'],
                $data['student_name'],
                $data['course_name'],
                $data['duration'],
                $data['certificate_no'],
                $data['completion_date']
            ]);

            // Fetch branding
            $settingsStmt = $db->query("SELECT * FROM settings");
            $settings = [];
            foreach ($settingsStmt->fetchAll() as $s) {
                $settings[$s['key_name']] = $s['key_value'];
            }

            // Render PDF
            $options = new Options();
            $options->set('isRemoteEnabled', true);
            $dompdf = new Dompdf($options);

            ob_start();
            include __DIR__ . '/../../views/admin/certificate_pdf.php';
            $html = ob_get_clean();

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

            $filename = "Certificate-" . str_replace(' ', '-', $data['student_name']) . ".pdf";
            $dompdf->stream($filename, ["Attachment" => false]);
            exit;
        }

        redirect('/admin/certificates');
    }

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

        $id = $_GET['id'] ?? null;
        if (!$id) {
            redirect('/admin/certificates');
            exit;
        }

        $db = \App\Core\Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM certificates WHERE id = ?");
        $stmt->execute([$id]);
        $cert = $stmt->fetch();

        if (!$cert) {
            redirect('/admin/certificates');
            exit;
        }

        $data = [
            'student_id' => $cert['student_id'],
            'student_name' => $cert['student_name'],
            'course_name' => $cert['course_name'],
            'duration' => $cert['duration'],
            'completion_date' => $cert['issue_date'],
            'certificate_no' => $cert['certificate_no']
        ];

        // Load template settings
        $settingsStmt = $db->query("SELECT * FROM settings");
        $settings = [];
        foreach ($settingsStmt->fetchAll() as $s) {
            $settings[$s['key_name']] = $s['key_value'];
        }

        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $dompdf = new Dompdf($options);

        ob_start();
        include __DIR__ . '/../../views/admin/certificate_pdf.php';
        $html = ob_get_clean();

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

        $filename = "Certificate-" . str_replace(' ', '-', $data['student_name']) . ".pdf";
        $dompdf->stream($filename, ["Attachment" => false]);
        exit;
    }
}
