<?php
namespace App\Services;

class PdfService {
    private $pdo;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }

    private function createPdf($options = []) {
        $defaults = ['margin_left' => 15, 'margin_right' => 15, 'margin_top' => 20, 'margin_bottom' => 20, 'mode' => 'utf-8', 'format' => 'A4'];
        return new \Mpdf\Mpdf(array_merge($defaults, $options));
    }

    private function getAcademyHeader(): string {
        $name = get_setting('academy_name', 'CIX Orbit Academy');
        $slogan = get_setting('slogan', 'Learn. Build. Automate. Grow.');
        return '<div style="text-align:center;border-bottom:3px solid #ff6b00;padding-bottom:15px;margin-bottom:20px;"><h1 style="color:#ff6b00;font-size:24px;margin:0;">' . e($name) . '</h1><p style="color:#666;margin:5px 0 0;font-size:12px;">' . e($slogan) . '</p></div>';
    }

    private function getAcademyFooter(): string {
        return '<div style="text-align:center;border-top:2px solid #ff6b00;padding-top:15px;margin-top:30px;color:#999;font-size:10px;"><p>Powered by CIX Connect | ' . e(get_setting('academy_url', '')) . '</p><p>Academic: ' . e(get_setting('academic_email', '')) . ' | Office: ' . e(get_setting('office_phone', '')) . '</p><p>Generated on ' . date('d M Y H:i') . '</p></div>';
    }

    private function getBaseStyle(): string {
        return 'body{font-family:DejaVu Sans,sans-serif;font-size:11px;color:#333;line-height:1.6;}table{width:100%;border-collapse:collapse;margin:10px 0;}th{background:#f5f5f5;padding:8px;text-align:left;border-bottom:2px solid #ddd;font-size:10px;text-transform:uppercase;}td{padding:8px;border-bottom:1px solid #eee;}.text-right{text-align:right;}.text-center{text-align:center;}.fw-bold{font-weight:bold;}.text-orange{color:#ff6b00;}.text-green{color:#00aa00;}.text-red{color:#cc0000;}.mb-1{margin-bottom:5px;}.mb-2{margin-bottom:10px;}.mb-3{margin-bottom:20px;}.mt-2{margin-top:10px;}.h3{font-size:16px;color:#333;margin:15px 0 8px;}.stat-row{display:flex;justify-content:center;gap:15px;margin:15px 0;}.stat-box{text-align:center;padding:12px 20px;border:1px solid #ddd;border-radius:8px;min-width:120px;}.stat-value{font-size:22px;font-weight:bold;color:#ff6b00;}.stat-label{font-size:9px;color:#666;text-transform:uppercase;}';
    }

    public function generateCertificate(int $certId): ?string {
        $stmt = $this->pdo->prepare("SELECT c.*, s.student_number, s.id as student_db_id, u.first_name, u.last_name, cr.title as course_title, cr.pass_mark FROM certificates c JOIN students s ON c.student_id = s.id JOIN users u ON s.user_id = u.id JOIN courses cr ON c.course_id = cr.id WHERE c.id = ?");
        $stmt->execute([$certId]);
        $cert = $stmt->fetch();
        if (!$cert) return null;

        $mpdf = $this->createPdf(['orientation' => 'L', 'format' => 'A4']);
        $html = '<!DOCTYPE html><html><head><style>
            body{font-family:DejaVu Sans,sans-serif;text-align:center;margin:0;padding:0;}
            .certificate{border:8px solid #ff6b00;padding:50px;position:relative;height:100%;box-sizing:border-box;}
            .watermark{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-30deg);font-size:60px;color:rgba(255,107,0,0.06);white-space:nowrap;pointer-events:none;font-weight:bold;}
            .border-inner{position:absolute;top:15px;left:15px;right:15px;bottom:15px;border:1px solid #00ff41;pointer-events:none;}
            .logo-area{margin-bottom:10px;}
            .logo-area h1{font-size:32px;color:#000;margin:0;}
            .logo-area h1 span{color:#ff6b00;}
            .logo-area p{color:#666;font-size:11px;margin:3px 0 0;}
            .cert-title{font-size:28px;color:#333;margin:15px 0 5px;font-weight:bold;letter-spacing:2px;}
            .cert-subtitle{font-size:14px;color:#666;margin-bottom:20px;}
            .cert-name{font-size:30px;font-weight:bold;color:#ff6b00;margin:20px 0;padding:10px;border-bottom:2px solid #ff6b00;display:inline-block;}
            .cert-course{font-size:16px;color:#333;margin:20px 0;font-style:italic;}
            .cert-details{font-size:11px;color:#666;margin:20px 0;}
            .cert-details table{margin:0 auto;border-collapse:collapse;}
            .cert-details td{padding:5px 15px;text-align:left;}
            .cert-details td:first-child{font-weight:bold;color:#333;}
            .qr{margin:15px auto;display:block;}
            .seal{width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,#ff6b00,#e65c00);margin:15px auto;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;font-size:14px;box-shadow:0 2px 10px rgba(255,107,0,0.3);}
            .signature-area{display:flex;justify-content:space-around;margin-top:25px;padding-top:10px;}
            .sig-line{width:200px;text-align:center;border-top:1px solid #333;padding-top:5px;font-size:10px;color:#666;}
        </style></head><body>
        <div class="certificate">
            <div class="border-inner"></div>
            <div class="watermark">CIX ORBIT ACADEMY</div>
            <div class="logo-area">
                <h1>CIX <span>Orbit</span> Academy</h1>
                <p>' . e(get_setting('slogan', 'Learn. Build. Automate. Grow.')) . '</p>
            </div>
            <div class="cert-title">CERTIFICATE OF COMPLETION</div>
            <div class="cert-subtitle">This is to certify that</div>
            <div class="cert-name">' . e($cert['student_name']) . '</div>
            <div class="cert-course">has successfully completed the course<br><strong>' . e($cert['course_title']) . '</strong></div>
            <div class="cert-details">
                <table>
                    <tr><td>Certificate Number:</td><td>' . e($cert['certificate_number']) . '</td></tr>
                    <tr><td>Student Number:</td><td>' . e($cert['student_number']) . '</td></tr>
                    <tr><td>Issue Date:</td><td>' . e($cert['issue_date']) . '</td></tr>
                    <tr><td>Final Mark:</td><td>' . e($cert['final_mark'] ?? 'N/A') . '%</td></tr>
                </table>
            </div>';
        if ($cert['qr_code_path'] && file_exists(__DIR__ . '/../../' . $cert['qr_code_path'])) {
            $html .= '<img src="' . __DIR__ . '/../../' . $cert['qr_code_path'] . '" class="qr" width="100">';
        }
        $html .= '<div class="seal">CIX</div>
            <div class="signature-area">
                <div class="sig-line">Academy Director</div>
                <div class="sig-line">Course Instructor</div>
            </div>
        </div></body></html>';
        
        $filepath = __DIR__ . '/../../storage/certificates/cert-' . $cert['certificate_number'] . '.pdf';
        $mpdf->WriteHTML($html);
        $mpdf->Output($filepath, \Mpdf\Output\Destination::FILE);
        $this->pdo->prepare("UPDATE certificates SET pdf_path = ? WHERE id = ?")->execute(['storage/certificates/cert-' . $cert['certificate_number'] . '.pdf', $certId]);
        return $filepath;
    }

    public function generateStudentReport(int $studentId): string {
        $html = '<!DOCTYPE html><html><head><style>' . $this->getBaseStyle() . '</style></head><body>';
        $html .= $this->getAcademyHeader();
        $html .= '<h3 class="h3">Student Progress Report</h3>';
        
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email, u.phone FROM students s JOIN users u ON s.user_id = u.id WHERE s.id = ?");
        $stmt->execute([$studentId]);
        $student = $stmt->fetch();
        if (!$student) return '';
        
        $html .= '<table><tr><td class="fw-bold">Name:</td><td>' . e($student['first_name'] . ' ' . $student['last_name']) . '</td><td class="fw-bold">Student #:</td><td class="text-orange fw-bold">' . e($student['student_number']) . '</td></tr>';
        $html .= '<tr><td class="fw-bold">Email:</td><td>' . e($student['email']) . '</td><td class="fw-bold">Phone:</td><td>' . e($student['phone'] ?? '-') . '</td></tr>';
        $html .= '<tr><td class="fw-bold">Enrollment:</td><td>' . e(ucfirst($student['enrollment_status'])) . '</td><td class="fw-bold">Payment:</td><td>' . e(ucfirst($student['payment_status'])) . '</td></tr></table>';
        
        $stmt = $this->pdo->prepare("SELECT e.*, c.title as course_title FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?");
        $stmt->execute([$studentId]);
        $enrollments = $stmt->fetchAll();
        if (!empty($enrollments)) {
            $html .= '<h3 class="h3">Enrolled Courses</h3><table><thead><tr><th>Course</th><th>Status</th><th>Progress</th><th>Enrolled</th></tr></thead><tbody>';
            foreach ($enrollments as $en) {
                $html .= '<tr><td>' . e($en['course_title']) . '</td><td>' . e(ucfirst($en['status'])) . '</td><td>' . ($en['progress_percent'] ?? 0) . '%</td><td>' . e($en['enrolled_at']) . '</td></tr>';
            }
            $html .= '</tbody></table>';
        }
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.title as test_title, c.title as course_title FROM test_attempts ta JOIN tests t ON ta.test_id = t.id JOIN courses c ON t.course_id = c.id WHERE ta.student_id = ? AND ta.status = 'completed' ORDER BY ta.ended_at DESC");
        $stmt->execute([$studentId]);
        $results = $stmt->fetchAll();
        if (!empty($results)) {
            $html .= '<h3 class="h3">Test Results</h3><table><thead><tr><th>Test</th><th>Course</th><th>Score</th><th>Status</th><th>Date</th></tr></thead><tbody>';
            foreach ($results as $r) {
                $html .= '<tr><td>' . e($r['test_title']) . '</td><td>' . e($r['course_title']) . '</td><td class="fw-bold text-orange">' . e($r['score']) . '%</td><td class="' . ($r['passed'] ? 'text-green' : 'text-red') . ' fw-bold">' . ($r['passed'] ? 'Passed' : 'Failed') . '</td><td>' . e($r['ended_at']) . '</td></tr>';
            }
            $html .= '</tbody></table>';
        }
        
        $html .= $this->getAcademyFooter() . '</body></html>';
        $filepath = __DIR__ . '/../../storage/reports/student-report-' . $studentId . '-' . date('Ymd') . '.pdf';
        generate_pdf($html, $filepath);
        return $filepath;
    }

    public function generateClassReport(int $courseId): string {
        $html = '<!DOCTYPE html><html><head><style>' . $this->getBaseStyle() . '</style></head><body>';
        $html .= $this->getAcademyHeader();
        
        $course = $this->pdo->prepare("SELECT * FROM courses WHERE id = ?");
        $course->execute([$courseId]);
        $course = $course->fetch();
        if (!$course) return '';
        
        $html .= '<h3 class="h3">Class Performance Report: ' . e($course['title']) . '</h3>';
        
        $stats = $this->pdo->prepare("SELECT AVG(ta.score) as avg_score, COUNT(DISTINCT ta.student_id) as total_students, SUM(CASE WHEN ta.passed = 1 THEN 1 ELSE 0 END) as passed FROM test_attempts ta JOIN tests t ON ta.test_id = t.id WHERE t.course_id = ? AND ta.status = 'completed'");
        $stats->execute([$courseId]);
        $s = $stats->fetch();
        
        $html .= '<div class="stat-row"><div class="stat-box"><div class="stat-value">' . ($s['total_students'] ?? 0) . '</div><div class="stat-label">Students</div></div><div class="stat-box"><div class="stat-value">' . ($s['avg_score'] ? round($s['avg_score'], 1) . '%' : 'N/A') . '</div><div class="stat-label">Avg Score</div></div><div class="stat-box"><div class="stat-value">' . ($s['total_students'] > 0 ? round(($s['passed'] / $s['total_students']) * 100, 1) . '%' : 'N/A') . '</div><div class="stat-label">Pass Rate</div></div></div>';
        
        $stmt = $this->pdo->prepare("SELECT s.student_number, u.first_name, u.last_name, e.progress_percent FROM enrollments e JOIN students s ON e.student_id = s.id JOIN users u ON s.user_id = u.id WHERE e.course_id = ? AND e.status = 'active' ORDER BY u.last_name");
        $stmt->execute([$courseId]);
        $students = $stmt->fetchAll();
        
        $html .= '<table><thead><tr><th>Student #</th><th>Name</th><th>Progress</th></tr></thead><tbody>';
        foreach ($students as $st) {
            $html .= '<tr><td class="text-orange fw-bold">' . e($st['student_number']) . '</td><td>' . e($st['first_name'] . ' ' . $st['last_name']) . '</td><td>' . ($st['progress_percent'] ?? 0) . '%</td></tr>';
        }
        $html .= '</tbody></table>';
        $html .= $this->getAcademyFooter() . '</body></html>';
        
        $filepath = __DIR__ . '/../../storage/reports/class-report-' . $courseId . '-' . date('Ymd') . '.pdf';
        generate_pdf($html, $filepath);
        return $filepath;
    }

    public function generatePaymentReport(): string {
        $html = '<!DOCTYPE html><html><head><style>' . $this->getBaseStyle() . '</style></head><body>';
        $html .= $this->getAcademyHeader();
        $html .= '<h3 class="h3">Payment Report</h3>';
        
        $totalApproved = (float)$this->pdo->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='approved'")->fetchColumn();
        $totalPending = (float)$this->pdo->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status IN ('pending','submitted')")->fetchColumn();
        $totalCount = (int)$this->pdo->query("SELECT COUNT(*) FROM payments")->fetchColumn();
        
        $html .= '<div class="stat-row"><div class="stat-box"><div class="stat-value">R' . number_format($totalApproved, 0) . '</div><div class="stat-label">Approved</div></div><div class="stat-box"><div class="stat-value">R' . number_format($totalPending, 0) . '</div><div class="stat-label">Pending</div></div><div class="stat-box"><div class="stat-value">' . $totalCount . '</div><div class="stat-label">Total Payments</div></div></div>';
        
        $stmt = $this->pdo->query("SELECT p.*, s.student_number, u.first_name, u.last_name, pk.name as package_name FROM payments p JOIN students s ON p.student_id = s.id JOIN users u ON s.user_id = u.id LEFT JOIN packages pk ON p.package_id = pk.id ORDER BY p.created_at DESC");
        $payments = $stmt->fetchAll();
        
        $html .= '<table><thead><tr><th>Student #</th><th>Name</th><th>Package</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead><tbody>';
        foreach ($payments as $p) {
            $html .= '<tr><td>' . e($p['student_number']) . '</td><td>' . e($p['first_name'] . ' ' . $p['last_name']) . '</td><td>' . e($p['package_name'] ?? '-') . '</td><td class="fw-bold text-orange">R' . number_format($p['amount'], 2) . '</td><td>' . e(ucfirst($p['status'])) . '</td><td>' . e($p['created_at']) . '</td></tr>';
        }
        $html .= '</tbody></table>';
        $html .= $this->getAcademyFooter() . '</body></html>';
        
        $filepath = __DIR__ . '/../../storage/reports/payment-report-' . date('Ymd') . '.pdf';
        generate_pdf($html, $filepath);
        return $filepath;
    }

    public function generateCertificateReport(): string {
        $html = '<!DOCTYPE html><html><head><style>' . $this->getBaseStyle() . '</style></head><body>';
        $html .= $this->getAcademyHeader();
        $html .= '<h3 class="h3">Certificates Issued Report</h3>';
        
        $certs = $this->pdo->query("SELECT c.*, s.student_number, u.first_name, u.last_name, cr.title as course_title FROM certificates c JOIN students s ON c.student_id = s.id JOIN users u ON s.user_id = u.id JOIN courses cr ON c.course_id = cr.id ORDER BY c.created_at DESC")->fetchAll();
        
        $html .= '<p class="fw-bold">Total Certificates: ' . count($certs) . '</p>';
        $html .= '<table><thead><tr><th>Certificate #</th><th>Student</th><th>Course</th><th>Issue Date</th><th>Status</th></tr></thead><tbody>';
        foreach ($certs as $c) {
            $html .= '<tr><td class="text-orange fw-bold">' . e($c['certificate_number']) . '</td><td>' . e($c['student_name']) . '</td><td>' . e($c['course_name']) . '</td><td>' . e($c['issue_date']) . '</td><td>' . e(ucfirst($c['status'])) . '</td></tr>';
        }
        $html .= '</tbody></table>';
        $html .= $this->getAcademyFooter() . '</body></html>';
        
        $filepath = __DIR__ . '/../../storage/reports/certificate-report-' . date('Ymd') . '.pdf';
        generate_pdf($html, $filepath);
        return $filepath;
    }

    public function generateApplicationReport(): string {
        $html = '<!DOCTYPE html><html><head><style>' . $this->getBaseStyle() . '</style></head><body>';
        $html .= $this->getAcademyHeader();
        $html .= '<h3 class="h3">Applications Report</h3>';
        
        $apps = $this->pdo->query("SELECT * FROM applications ORDER BY created_at DESC")->fetchAll();
        $pending = $approved = $rejected = 0;
        foreach ($apps as $a) { if ($a['status'] === 'pending') $pending++; elseif ($a['status'] === 'accepted') $approved++; else $rejected++; }
        
        $html .= '<div class="stat-row"><div class="stat-box"><div class="stat-value">' . count($apps) . '</div><div class="stat-label">Total</div></div><div class="stat-box"><div class="stat-value">' . $pending . '</div><div class="stat-label">Pending</div></div><div class="stat-box"><div class="stat-value">' . $approved . '</div><div class="stat-label">Accepted</div></div><div class="stat-box"><div class="stat-value">' . $rejected . '</div><div class="stat-label">Rejected</div></div></div>';
        
        $html .= '<table><thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Province</th><th>Status</th><th>Date</th></tr></thead><tbody>';
        foreach (array_slice($apps, 0, 100) as $a) {
            $html .= '<tr><td>' . e($a['first_name'] . ' ' . $a['last_name']) . '</td><td>' . e($a['email']) . '</td><td>' . e($a['phone']) . '</td><td>' . e($a['province'] ?? '-') . '</td><td>' . e(ucfirst($a['status'])) . '</td><td>' . e($a['created_at']) . '</td></tr>';
        }
        $html .= '</tbody></table>';
        $html .= $this->getAcademyFooter() . '</body></html>';
        
        $filepath = __DIR__ . '/../../storage/reports/application-report-' . date('Ymd') . '.pdf';
        generate_pdf($html, $filepath);
        return $filepath;
    }
}
