<?php
require_once '../../config.php';
check_login();

if (!isset($_GET['id'])) {
    header('Location: /dashboard/');
    exit;
}

$application_id = (int)$_GET['id'];
$application = get_application_details($application_id);

// Check if user has permission to view this application
if (!has_application_access($_SESSION['user']['id'], $application_id)) {
    header('Location: /dashboard/');
    exit;
}

// Generate PDF
require_once '../../lib/tcpdf/tcpdf.php';

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set document information
$pdf->SetCreator('JV Overseas Education');
$pdf->SetAuthor('JV Overseas Education');
$pdf->SetTitle('Application Report - ' . $application['student_name']);
$pdf->SetSubject('Application Details');
$pdf->SetKeywords('Application, Student, University');

// Set margins
$pdf->SetMargins(15, 15, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(10);

// Add a page
$pdf->AddPage();

// Add logo
$pdf->Image('../../img/logo.png', 15, 10, 40, '', 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false);

// Set font
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 20, 'Application Report', 0, 1, 'C');
$pdf->Ln(10);

// Student information
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 0, 'Student Information', 0, 1);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(60, 6, 'Name:', 0, 0);
$pdf->Cell(0, 6, $application['student_name'], 0, 1);
$pdf->Cell(60, 6, 'Email:', 0, 0);
$pdf->Cell(0, 6, $application['student_email'], 0, 1);
$pdf->Cell(60, 6, 'Phone:', 0, 0);
$pdf->Cell(0, 6, $application['student_phone'], 0, 1);
$pdf->Ln(5);

// Application details
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 0, 'Application Details', 0, 1);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(60, 6, 'University:', 0, 0);
$pdf->Cell(0, 6, $application['university_name'], 0, 1);
$pdf->Cell(60, 6, 'Program:', 0, 0);
$pdf->Cell(0, 6, $application['program_name'], 0, 1);
$pdf->Cell(60, 6, 'Intake:', 0, 0);
$pdf->Cell(0, 6, $application['intake_month'] . ' ' . $application['intake_year'], 0, 1);
$pdf->Cell(60, 6, 'Status:', 0, 0);
$pdf->Cell(0, 6, ucfirst(str_replace('_', ' ', $application['application_status'])), 0, 1);
$pdf->Cell(60, 6, 'Submitted:', 0, 0);
$pdf->Cell(0, 6, format_date($application['submission_date']), 0, 1);
$pdf->Ln(5);

// Documents
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 0, 'Submitted Documents', 0, 1);
$pdf->SetFont('helvetica', '', 10);

$documents = get_application_documents($application_id);
if (!empty($documents)) {
    foreach ($documents as $doc) {
        $pdf->Cell(80, 6, ucfirst(str_replace('_', ' ', $doc['document_type'])), 0, 0);
        $pdf->Cell(0, 6, ucfirst($doc['status']), 0, 1);
    }
} else {
    $pdf->Cell(0, 6, 'No documents submitted yet', 0, 1);
}

// Output PDF
$pdf->Output('application_' . $application_id . '.pdf', 'I');