<?php
// school_admission/public/view_admission_letter.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'; // Keep this for isLoggedIn() and other potential functions


$letter_id = isset($_GET['letter_id']) ? (int)$_GET['letter_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;


// --- INLINE AUTHORIZATION LOGIC (REPLACING requireAnyRole()) ---
// Check if user is logged in at all
if (!isLoggedIn()) { // Using isLoggedIn() from auth_check.php
    die("Access denied! Please login to view admission letters. <p><a href='login.php'>Login Here</a></p>");
}

// Define allowed roles directly
$allowed_roles = ['super_admin', 'branch_admin'];

// Check if the logged-in user's role is within the allowed roles
if (!in_array($user_role, $allowed_roles)) {
    die("Access denied! You do not have the necessary permissions to view admission letters.");
}
// --- END INLINE AUTHORIZATION LOGIC ---


if ($letter_id === 0) {
    die("Invalid letter ID.");
}

$letter_content = null;

try {
    // Fetch letter content and verify permissions
    $sql = "SELECT al.letter_content, al.applicant_id, a.branch_id
            FROM admission_letters al
            JOIN applicants a ON al.applicant_id = a.applicant_id
            WHERE al.letter_id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Database prepare error: " . $conn->error);
    }
    $stmt->bind_param("i", $letter_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("Admission letter not found.");
    }

    $letter_data = $result->fetch_assoc();
    $stmt->close();

    // Additional permission check for Branch Admins
    // Super Admin can view any letter. Branch Admin can only view letters from their branch.
    if ($user_role === 'branch_admin' && $letter_data['branch_id'] != $user_branch_id) {
        die("You do not have permission to view this letter. It belongs to another branch.");
    }

    $letter_content = $letter_data['letter_content'];

    // Update printed_at and printed_by_user_id (only if not already printed, or if you want to track multiple prints)
    $current_datetime = date('Y-m-d H:i:s');
    // Using a simple check: if printed_at is NULL, set it. Otherwise, don't overwrite if you only want to record first print.
    // If you want to update 'printed_at' every time, remove 'AND printed_at IS NULL'
    $stmt_update_print = $conn->prepare("UPDATE admission_letters SET printed_at = ?, printed_by_user_id = ? WHERE letter_id = ? AND printed_at IS NULL");
    
    if ($stmt_update_print) {
        $stmt_update_print->bind_param("sii", $current_datetime, $user_id, $letter_id);
        $stmt_update_print->execute();
        $stmt_update_print->close();
    } else {
        error_log("Failed to prepare statement for updating print status: " . $conn->error);
    }

} catch (Exception $e) {
    // In case of error, just display a basic error message directly as text
    header("HTTP/1.0 500 Internal Server Error"); // Send a 500 header for internal errors
    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();
}

// Output the raw HTML content of the letter
// This ensures that the letter is rendered with its own styling (from the template)
// and is ready for the browser's print functionality.
echo $letter_content;

$conn->close();
exit(); // Ensure nothing else is outputted after the letter content
?>