<?php
// school_admission/public/admin_application_details.php
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';

requireRole(['super_admin']); // Only Super Admin can access this page

$message = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

$applicant_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$applicant = null;
$academic_records = [];
$uploaded_documents = [];

if ($applicant_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid applicant ID.</div>";
    redirect('admin_view_applications.php');
}

// Fetch applicant's main details
$stmt_applicant = $conn->prepare("
    SELECT
        a.*,
        c.course_name,
        b.branch_name
    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 === 1) {
    $applicant = $result_applicant->fetch_assoc();
} else {
    $_SESSION['message'] = "<div class='message error'>Applicant not found.</div>";
    redirect('admin_view_applications.php');
}
$stmt_applicant->close();

// 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();

// Fetch uploaded documents
$stmt_docs = $conn->prepare("SELECT * FROM uploaded_documents WHERE applicant_id = ? ORDER BY uploaded_at ASC");
$stmt_docs->bind_param("i", $applicant_id);
$stmt_docs->execute();
$result_docs = $stmt_docs->get_result();
while ($row = $result_docs->fetch_assoc()) {
    $uploaded_documents[] = $row;
}
$stmt_docs->close();

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">Application Details: <?php echo htmlspecialchars($applicant['first_name'] . ' ' . $applicant['last_name']); ?></h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<div class="application-details-card">
    <h3>Applicant Information</h3>
    <p><strong>Application No:</strong> <?php echo htmlspecialchars($applicant['application_no']); ?></p>
    <p><strong>Status:</strong> <span class="status-<?php echo strtolower(str_replace(' ', '-', $applicant['status'])); ?>"><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $applicant['status']))); ?></span></p>
    <p><strong>Applied From Branch:</strong> <?php echo htmlspecialchars($applicant['branch_name']); ?></p>
    <p><strong>First Name:</strong> <?php echo htmlspecialchars($applicant['first_name']); ?></p>
    <p><strong>Last Name:</strong> <?php echo htmlspecialchars($applicant['last_name']); ?></p>
    <p><strong>Other Names:</strong> <?php echo htmlspecialchars($applicant['other_names']); ?></p>
    <p><strong>Date of Birth:</strong> <?php echo date('d-M-Y', strtotime($applicant['date_of_birth'])); ?></p>
    <p><strong>Gender:</strong> <?php echo htmlspecialchars($applicant['gender']); ?></p>
    <p><strong>Address:</strong> <?php echo nl2br(htmlspecialchars($applicant['address'])); ?></p>
    <p><strong>Phone Number:</strong> <?php echo htmlspecialchars($applicant['phone_number']); ?></p>
    <p><strong>Email:</strong> <?php echo htmlspecialchars($applicant['email']); ?></p>
    <p><strong>Applied Course:</strong> <?php echo htmlspecialchars($applicant['course_name']); ?></p>
    <p><strong>Level:</strong> <?php echo htmlspecialchars($applicant['level']); ?></p>
    <p><strong>Application Date:</strong> <?php echo date('d-M-Y', strtotime($applicant['application_date'])); ?></p>
</div>

<h3 class="mt-30">Academic Records</h3>
<?php if (empty($academic_records)): ?>
    <div class="message info">No academic records found for this applicant.</div>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Exam Type</th>
                <th>Year</th>
                <th>Subject</th>
                <th>Grade</th>
                <th>Attachment</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($academic_records as $record): ?>
                <tr>
                    <td data-label="Exam Type"><?php echo htmlspecialchars($record['exam_type']); ?></td>
                    <td data-label="Year"><?php echo htmlspecialchars($record['exam_year']); ?></td>
                    <td data-label="Subject"><?php echo htmlspecialchars($record['subject']); ?></td>
                    <td data-label="Grade"><?php echo htmlspecialchars($record['grade']); ?></td>
                    <td data-label="Attachment">
                        <?php if ($record['attachment_path']): ?>
                            <a href="<?php echo htmlspecialchars($record['attachment_path']); ?>" target="_blank" class="btn btn-info btn-sm"><i class="fas fa-file-alt"></i> View</a>
                        <?php else: ?>
                            N/A
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

<h3 class="mt-30">Uploaded Documents</h3>
<?php if (empty($uploaded_documents)): ?>
    <div class="message info">No general documents found for this applicant.</div>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Document Type</th>
                <th>File</th>
                <th>Uploaded On</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($uploaded_documents as $doc): ?>
                <tr>
                    <td data-label="Document Type"><?php echo htmlspecialchars($doc['document_type']); ?></td>
                    <td data-label="File">
                        <?php if ($doc['file_path']): ?>
                            <a href="<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank" class="btn btn-info btn-sm"><i class="fas fa-file-alt"></i> View</a>
                        <?php else: ?>
                            N/A
                        <?php endif; ?>
                    </td>
                    <td data-label="Uploaded On"><?php echo date('d-M-Y H:i', strtotime($doc['uploaded_at'])); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

<div class="form-group mt-30 text-center">
    <?php if ($applicant['status'] === 'pending_review'): ?>
        <a href="admin_approve_application_action.php?id=<?php echo $applicant_id; ?>" class="btn btn-success confirm-action"><i class="fas fa-check-circle"></i> Approve Application</a>
        <a href="admin_reject_application_action.php?id=<?php echo $applicant_id; ?>" class="btn btn-danger confirm-action"><i class="fas fa-times-circle"></i> Reject Application</a>
    <?php elseif ($applicant['status'] === 'approved' || $applicant['status'] === 'admission_letter_generated'): ?>
        <a href="#" class="btn btn-info disabled-btn" style="pointer-events: none; opacity: 0.6;"><i class="fas fa-check-circle"></i> Already Approved</a>
    <?php elseif ($applicant['status'] === 'rejected'): ?>
        <a href="#" class="btn btn-danger disabled-btn" style="pointer-events: none; opacity: 0.6;"><i class="fas fa-times-circle"></i> Already Rejected</a>
    <?php endif; ?>
    <a href="print_application_data.php?id=<?php echo $applicant_id; ?>" target="_blank" class="btn btn-primary"><i class="fas fa-file-invoice"></i> Print Application Data</a>
    <a href="admin_view_applications.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back to All Applications</a>
</div>

<style>
/* Additional CSS for Application Details Page */
.application-details-card {
    background-color: #ffffff;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: 30px;
    border: 1px solid #e0e0e0;
}
.application-details-card h3 {
    color: #1a4a8d;
    font-size: 1.6em;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
}
.application-details-card p {
    margin-bottom: 10px;
    font-size: 1.05em;
    line-height: 1.5;
}
.application-details-card p strong {
    color: #34495e;
    min-width: 150px; /* Align labels */
    display: inline-block;
}
.disabled-btn {
    cursor: not-allowed;
    opacity: 0.6;
}
</style>
<script>
    // Add confirmation for approve/reject actions
    document.addEventListener('DOMContentLoaded', function() {
        const confirmButtons = document.querySelectorAll('.confirm-action');
        confirmButtons.forEach(button => {
            button.addEventListener('click', function(event) {
                const action = this.textContent.trim().split(' ')[0]; // "Approve" or "Reject"
                if (!confirm(`Are you sure you want to ${action.toLowerCase()} this application? This action cannot be easily undone.`)) {
                    event.preventDefault();
                }
            });
        });
    });
</script>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>