<?php
// school_admission/public/print_application_data.php

// --- DEBUGGING LINES START ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- DEBUGGING LINES END ---

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php'; // Needed for isLoggedIn()


$applicant_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
$user_role = isset($_SESSION['role']) ? $_SESSION['role'] : null;
$user_branch_id = isset($_SESSION['branch_id']) ? $_SESSION['branch_id'] : null;

if ($applicant_id === 0) {
    die("Invalid applicant ID.");
}

// --- INLINE AUTHORIZATION LOGIC ---
if (!isLoggedIn()) {
    die("Access denied! Please login to view application data. <p><a href='login.php'>Login Here</a></p>");
}
$allowed_roles = ['super_admin', 'branch_admin'];
if (!in_array($user_role, $allowed_roles)) {
    die("Access denied! You do not have the necessary permissions to view application data.");
}
// --- END INLINE AUTHORIZATION LOGIC ---


$applicant_data = null;
$academic_records = [];
$passport_photo_path = null;
$branch_data = null;
$course_data = null;

try {
    // 1. Fetch ALL applicant data including new fields
    $stmt_applicant = $conn->prepare("
        SELECT
            a.*,
            c.course_name, c.course_code, c.description AS course_description,
            b.branch_name, b.location AS branch_location, b.contact_email AS branch_email, b.contact_phone AS branch_phone
        FROM
            applicants a
        JOIN
            courses c ON a.course_id = c.course_id
        JOIN
            branches b ON a.branch_id = b.branch_id
        WHERE
            a.applicant_id = ?
    ");
    $stmt_applicant->bind_param("i", $applicant_id);
    $stmt_applicant->execute();
    $result_applicant = $stmt_applicant->get_result();

    if ($result_applicant->num_rows === 0) {
        throw new Exception("Applicant not found.");
    }
    $applicant_data = $result_applicant->fetch_assoc();
    $stmt_applicant->close();

    // 2. Branch Admin specific check
    if ($user_role === 'branch_admin' && $applicant_data['branch_id'] != $user_branch_id) {
        die("You do not have permission to view this applicant's data. It belongs to another branch.");
    }

    // 3. Fetch academic records
    $stmt_acad = $conn->prepare("SELECT * FROM academic_records WHERE applicant_id = ? ORDER BY record_id ASC");
    $stmt_acad->bind_param("i", $applicant_id);
    $stmt_acad->execute();
    $result_acad = $stmt_acad->get_result();
    while ($row = $result_acad->fetch_assoc()) {
        $academic_records[] = $row;
    }
    $stmt_acad->close();

    // 4. Fetch passport photo path
    $stmt_passport = $conn->prepare("SELECT file_path FROM uploaded_documents WHERE applicant_id = ? AND document_type = 'Passport Photo' ORDER BY uploaded_at DESC LIMIT 1");
    $stmt_passport->bind_param("i", $applicant_id);
    $stmt_passport->execute();
    $result_passport = $stmt_passport->get_result();
    if ($row = $result_passport->fetch_assoc()) {
        $passport_photo_path = $row['file_path'];
    }
    $stmt_passport->close();

    // Extract course and branch data from applicant_data for clarity in template
    $course_data = [
        'course_name' => $applicant_data['course_name'],
        'course_code' => $applicant_data['course_code'],
        'description' => $applicant_data['course_description']
    ];
    $branch_data = [
        'branch_name' => $applicant_data['branch_name'],
        'location' => $applicant_data['branch_location'],
        'contact_email' => $applicant_data['branch_email'],
        'contact_phone' => $applicant_data['branch_phone']
    ];


} catch (Exception $e) {
    header("HTTP/1.0 500 Internal Server Error");
    echo "<!DOCTYPE html><html><head><title>Error</title><style>body { font-family: Arial, sans-serif; background-color: #f8d7da; color: #721c24; padding: 20px; text-align: center; } h1 { color: #dc3545; } a { color: #007bff; text-decoration: none; }</style></head><body><h1>Server Error</h1><p>" . htmlspecialchars($e->getMessage()) . "</p><p>Please check the server logs for more details.</p><p><a href='javascript:history.back()'>Go Back</a></p></body></html>";
    exit();
}

ob_start(); // Start output buffering
include __DIR__ . '/../views/templates/application_data_template.php'; // Include the template
$printout_content = ob_get_clean(); // Get the HTML content

echo $printout_content;

$conn->close();
exit();
?>