<?php
/**
 * IBVTE Admin – View Student Details
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db   = DB();
$user = Auth()->getUser();
$id   = intval($_GET['id'] ?? 0);
$flash = getFlashMessage();

$student = $db->fetchOne("
    SELECT s.*, c.course_name, c.course_code, c.duration_text as duration_label, cat.name as category,
           sub.name as sub_name,
           u.institution_name, u.institution_code
    FROM students s
    LEFT JOIN courses c ON s.course_id = c.id
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_sub_categories sub ON c.sub_category_id = sub.id
    LEFT JOIN users u ON s.institution_id = u.id
    WHERE s.id = ?
", [$id]);

if (!$student) {
    redirectWithMessage('students.php', 'Student not found.', 'danger');
}

// Decode JSON arrays
$qualifications = [];
if (!empty($student['qualifications_json'])) {
    $qualifications = json_decode($student['qualifications_json'], true) ?: [];
}

$docs = [];
if (!empty($student['documents_attached'])) {
    $docs = json_decode($student['documents_attached'], true) ?: [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Student Profile – Admin Panel – <?= APP_SHORT_NAME ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="../assets/css/admin-style.css" rel="stylesheet">
<style>
:root{--primary:#3b0b7c;--secondary:#6c4ab6;}
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 15px;
}
.info-card {
    background: #fdfcff;
    border: 1px solid #efeaf8;
    border-radius: 10px;
    padding: 12px 15px;
    transition: all 0.2s;
}
.info-card:hover {
    box-shadow: 0 4px 12px rgba(92, 74, 182, 0.05);
}
.info-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    font-weight: 700;
    color: #8c7db3;
    margin-bottom: 2px;
}
.info-val {
    font-size: 0.95rem;
    font-weight: 600;
    color: #2b2342;
}
.student-photo{width:130px;height:165px;object-fit:cover;border-radius:12px;border:3px solid #e0d8f0;}
.reg-badge{font-family:monospace;background:linear-gradient(135deg,var(--primary),var(--secondary));color:white;padding:6px 18px;border-radius:20px;font-size:1rem;font-weight:700;letter-spacing:.05em;}
.sect-title {
    font-weight: 700;
    color: var(--primary);
    border-left: 4px solid var(--secondary);
    padding-left: 12px;
    margin: 30px 0 15px;
    font-size: 1.05rem;
    display: flex;
    align-items: center;
    gap: 8px;
}
</style>
</head>
<body>
<?php include __DIR__ . '/../includes/admin_header.php'; ?>
<div class="container-fluid">
<div class="row">
<?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">

<?php if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm rounded-3">
    <?= htmlspecialchars($flash['message']) ?><button class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
    <div>
        <a href="students.php" class="btn btn-outline-secondary btn-sm mb-2 shadow-sm me-2">
            <i class="fas fa-arrow-left me-1"></i>Back to Students List
        </a>
        <a href="edit-student.php?id=<?= $id ?>" class="btn btn-primary btn-sm mb-2 shadow-sm">
            <i class="fas fa-edit me-1"></i>Edit Student Details
        </a>
        <h2 class="h3 fw-bold mb-0 text-dark"><i class="fas fa-user-graduate text-primary me-2"></i>Student Registration Review</h2>
    </div>
    <span class="reg-badge shadow"><?= htmlspecialchars($student['registration_number'] ?? 'N/A') ?></span>
</div>

<div class="row g-4">
    <!-- Left Photo & Review Control Panel -->
    <div class="col-md-3">
        <div class="card border-0 shadow-sm rounded-4 text-center p-4">
            <?php if (!empty($student['photo_path']) && file_exists('../' . $student['photo_path'])): ?>
                <img src="../<?= htmlspecialchars($student['photo_path']) ?>" class="student-photo mx-auto d-block mb-3 shadow-sm" alt="Photo">
            <?php else: ?>
                <div class="student-photo mx-auto d-flex align-items-center justify-content-center mb-3 shadow-sm" style="background:#f0ebf8;">
                    <i class="fas fa-user fa-3x text-secondary opacity-50"></i>
                </div>
            <?php endif; ?>
            <h5 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($student['full_name']) ?></h5>
            <div class="badge bg-light text-primary mb-3 border fw-bold"><?= htmlspecialchars($student['institution_code'] ?? 'Direct') ?></div>
            
            <div class="mt-2">
                <?php
                $ap = $student['approval_status'] ?? 'pending';
                $cls = match($ap){ 'approved'=>'bg-success','rejected'=>'bg-danger',default=>'bg-warning text-dark'};
                ?>
                <span class="badge <?= $cls ?> fs-6 px-3 py-2 w-100 rounded-pill shadow-sm mb-3"><?= strtoupper($ap) ?></span>
            </div>

            <?php if ($ap === 'pending'): ?>
            <div class="d-grid gap-2 border-top pt-3">
                <a href="students.php?action=approve&id=<?= $id ?>" class="btn btn-success fw-bold py-2 shadow-sm" onclick="return confirm('Approve this student admission?')">
                    <i class="fas fa-check-circle me-1"></i>APPROVE ADMISSION
                </a>
                <a href="students.php?action=reject&id=<?= $id ?>" class="btn btn-outline-danger fw-bold py-2 btn-sm" onclick="return confirm('Reject this student admission?')">
                    <i class="fas fa-times-circle me-1"></i>REJECT
                </a>
            </div>
            <?php endif; ?>
            
            <hr class="my-4 opacity-50">
            
            <div class="text-start">
                <div class="small text-muted fw-bold text-uppercase mb-2">Registration ID</div>
                <div class="mb-2"><small class="fw-bold text-secondary">Roll Number:</small><br><span class="fw-bold text-danger"><?= formatRollNumber($student['roll_number'] ?? '-') ?></span></div>
                <div class="mb-2"><small class="fw-bold text-secondary">Submitted On:</small><br><span class="small fw-semibold"><?= formatDate($student['created_at'], 'd/m/Y, h:i A') ?></span></div>
            </div>
        </div>
    </div>

    <!-- Right Detailed 6-Section Panel -->
    <div class="col-md-9 mb-5">
        <div class="card border-0 shadow-sm rounded-4 p-4">
            
            <!-- COURSE & AFFILIATED COLLEGE DETAILS -->
            <div class="sect-title mt-0"><i class="fas fa-university"></i>Center & Course Selection</div>
            <div class="info-grid">
                <div class="info-card"><div class="info-label">Affiliated College/Center</div><div class="info-val fw-bold text-primary"><?= htmlspecialchars($student['institution_name'] ?? 'Direct') ?> (<?= htmlspecialchars($student['institution_code'] ?? '000') ?>)</div></div>
                <div class="info-card"><div class="info-label">Main Course</div><div class="info-val"><?= htmlspecialchars($student['course_name'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Sub Course</div><div class="info-val"><?= htmlspecialchars($student['sub_name'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Session</div><div class="info-val"><?= htmlspecialchars($student['session_year'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Duration</div><div class="info-val"><?= htmlspecialchars($student['duration_label'] ?? $student['duration'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Admission Date</div><div class="info-val"><?= formatDate($student['admission_date']) ?></div></div>
            </div>

            <!-- SECTION 1: PERSONAL DETAILS -->
            <div class="sect-title"><i class="fas fa-user-circle"></i>SECTION 1: PERSONAL DETAILS</div>
            <div class="info-grid">
                <div class="info-card"><div class="info-label">Student Name</div><div class="info-val"><?= htmlspecialchars($student['full_name']) ?></div></div>
                <div class="info-card"><div class="info-label">Father's Name</div><div class="info-val"><?= htmlspecialchars($student['father_name'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Mother's Name</div><div class="info-val"><?= htmlspecialchars($student['mother_name'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Guardian's Name</div><div class="info-val"><?= htmlspecialchars($student['guardian_name'] ?? 'N/A') ?></div></div>
                <div class="info-card"><div class="info-label">Date of Birth</div><div class="info-val"><?= formatDOB($student['date_of_birth']) ?></div></div>
                <div class="info-card"><div class="info-label">Gender</div><div class="info-val"><?= htmlspecialchars($student['gender'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Blood Group</div><div class="info-val"><?= htmlspecialchars($student['blood_group'] ?? 'Not Specified') ?></div></div>
                <div class="info-card"><div class="info-label">Aadhaar No.</div><div class="info-val"><?= htmlspecialchars($student['aadhaar_no'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Mobile No.</div><div class="info-val"><?= htmlspecialchars($student['mobile'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Email ID</div><div class="info-val"><?= htmlspecialchars($student['email'] ?? 'N/A') ?></div></div>
                <div class="info-card"><div class="info-label">Religion</div><div class="info-val"><?= htmlspecialchars($student['religion'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Category</div><div class="info-val"><span class="badge bg-secondary"><?= htmlspecialchars($student['category'] ?? '-') ?></span></div></div>
                <div class="info-card"><div class="info-label">Domicile State</div><div class="info-val"><?= htmlspecialchars($student['domicile_state'] ?? '-') ?></div></div>
            </div>

            <!-- SECTION 2: ADDRESS DETAILS -->
            <div class="sect-title"><i class="fas fa-map-marked-alt"></i>SECTION 2: ADDRESS DETAILS</div>
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="p-3 rounded-3 border bg-light h-100">
                        <div class="fw-bold text-primary mb-2 small text-uppercase"><i class="fas fa-home me-1"></i>Permanent Address</div>
                        <div class="small text-dark">
                            <?= nl2br(htmlspecialchars($student['permanent_address'] ?? $student['address'] ?? '-')) ?><br>
                            <strong>District:</strong> <?= htmlspecialchars($student['permanent_district'] ?? $student['city'] ?? '-') ?><br>
                            <strong>State:</strong> <?= htmlspecialchars($student['permanent_state'] ?? $student['state'] ?? '-') ?><br>
                            <strong>Pin Code:</strong> <?= htmlspecialchars($student['permanent_pincode'] ?? $student['pincode'] ?? '-') ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="p-3 rounded-3 border bg-light h-100">
                        <div class="fw-bold text-primary mb-2 small text-uppercase"><i class="fas fa-envelope me-1"></i>Correspondence Address</div>
                        <div class="small text-dark">
                            <?= nl2br(htmlspecialchars($student['correspondence_address'] ?? $student['address'] ?? '-')) ?><br>
                            <strong>District:</strong> <?= htmlspecialchars($student['correspondence_district'] ?? $student['city'] ?? '-') ?><br>
                            <strong>State:</strong> <?= htmlspecialchars($student['correspondence_state'] ?? $student['state'] ?? '-') ?><br>
                            <strong>Pin Code:</strong> <?= htmlspecialchars($student['correspondence_pincode'] ?? $student['pincode'] ?? '-') ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SECTION 3: EDUCATIONAL QUALIFICATION -->
            <div class="sect-title"><i class="fas fa-graduation-cap"></i>SECTION 3: EDUCATIONAL QUALIFICATION</div>
            <div class="table-responsive rounded-3 border">
                <table class="table table-bordered table-striped align-middle mb-0 text-center small">
                    <thead class="table-dark">
                        <tr>
                            <th>S.No</th>
                            <th>Exam Passed</th>
                            <th>Board / University</th>
                            <th>Year of Passing</th>
                            <th>Roll No.</th>
                            <th>Percentage / Division</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($qualifications)): ?>
                            <tr><td colspan="6" class="text-muted py-3">No educational qualifications recorded.</td></tr>
                        <?php else: ?>
                            <?php foreach ($qualifications as $i => $q): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>
                                    <td class="fw-bold text-start ps-3"><?= htmlspecialchars($q['exam_passed'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($q['board_university'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($q['year_of_passing'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($q['roll_no'] ?? '-') ?></td>
                                    <td class="fw-bold text-primary"><?= htmlspecialchars($q['percentage_division'] ?? '-') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- SECTION 4: DOCUMENTS ATTACHED -->
            <div class="sect-title"><i class="fas fa-paperclip"></i>SECTION 4: DOCUMENTS ATTACHED</div>
            <div class="p-3 bg-light rounded-3 border">
                <?php if (empty($docs)): ?>
                    <span class="text-muted">No documents marked.</span>
                <?php else: ?>
                    <div class="d-flex flex-wrap gap-2">
                        <?php foreach ($docs as $key => $val): 
                            $docName = is_numeric($key) ? $val : $key;
                            $docPath = is_numeric($key) ? '' : $val;
                        ?>
                            <span class="badge bg-primary px-3 py-2 d-inline-flex align-items-center gap-2">
                                <i class="fas fa-check-circle"></i>
                                <span><?= htmlspecialchars($docName) ?></span>
                                <?php if (!empty($docPath)): ?>
                                    <a href="../<?= htmlspecialchars($docPath) ?>" target="_blank" class="text-white border border-light rounded-circle p-1 ms-1 d-inline-flex align-items-center justify-content-center" style="width:18px;height:18px;font-size:0.65rem;" title="View Uploaded File">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                <?php endif; ?>
                            </span>
                        <?php endforeach; ?>
                        <?php if (!empty($student['documents_attached_other'])): ?>
                            <span class="badge bg-dark px-3 py-2"><i class="fas fa-paperclip me-1"></i>Other: <?= htmlspecialchars($student['documents_attached_other']) ?></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- SECTION 5: FEE DETAILS -->
            <div class="sect-title"><i class="fas fa-rupee-sign"></i>SECTION 5: FEE DETAILS (Student Payment Details)</div>
            <div class="info-grid mb-3">
                <div class="info-card"><div class="info-label">Admission Fee Charged</div><div class="info-val fw-semibold">₹<?= number_format($student['admission_fee'] ?? 0, 2) ?></div></div>
                <div class="info-card"><div class="info-label">Registration Fee Charged</div><div class="info-val fw-semibold">₹<?= number_format($student['registration_fee'] ?? 0, 2) ?></div></div>
                <div class="info-card" style="border-color: var(--secondary);"><div class="info-label text-primary">Total Paid by Student</div><div class="info-val text-primary fw-bold">₹<?= number_format(($student['admission_fee'] ?? 0) + ($student['registration_fee'] ?? 0), 2) ?></div></div>
                <div class="info-card"><div class="info-label">Payment Mode</div><div class="info-val"><?= htmlspecialchars($student['payment_mode'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Receipt / Transaction ID</div><div class="info-val text-uppercase"><?= htmlspecialchars($student['payment_receipt_no'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Payment Date</div><div class="info-val"><?= !empty($student['payment_date']) ? formatDate($student['payment_date']) : '-' ?></div></div>
            </div>
            
            <!-- TRAINING CENTER FEES DEDUCTION -->
            <div class="p-3 bg-light rounded-3 border mb-4">
                <div class="small fw-semibold text-secondary"><i class="fas fa-wallet text-secondary me-2"></i>Institutional Fee Deducted from Prepaid Wallet: <strong class="text-success">₹<?= number_format($student['total_fee'] ?? 0, 2) ?></strong></div>
            </div>

            <!-- SECTION 6: DECLARATION BY STUDENT / PARENT -->
            <div class="sect-title"><i class="fas fa-file-contract"></i>SECTION 6: DECLARATION & SIGNATURES</div>
            <div class="p-3 bg-light rounded-3 border">
                <div class="p-3 bg-white rounded border border-warning mb-4 shadow-sm text-justify small fw-semibold">
                    "I hereby declare that the information furnished above is true and correct to the best of my knowledge. I agree to abide by all rules, regulations, fee policies, and examination norms of the Board/Institution."
                </div>
                
                <div class="row g-4 text-center">
                    <div class="col-md-6 border-end">
                        <div class="fw-bold text-secondary small mb-2 text-uppercase">Student Signature</div>
                        <?php if (!empty($student['student_signature_path']) && file_exists('../' . $student['student_signature_path'])): ?>
                            <img src="../<?= htmlspecialchars($student['student_signature_path']) ?>" class="img-thumbnail shadow-sm bg-white" style="max-height: 90px; max-width: 220px;" alt="Student Signature">
                        <?php else: ?>
                            <div class="p-3 text-muted border border-dashed rounded bg-white small" style="max-height: 90px;">No signature uploaded</div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="fw-bold text-secondary small mb-2 text-uppercase">Parent / Guardian Signature</div>
                        <?php if (!empty($student['parent_signature_path']) && file_exists('../' . $student['parent_signature_path'])): ?>
                            <img src="../<?= htmlspecialchars($student['parent_signature_path']) ?>" class="img-thumbnail shadow-sm bg-white" style="max-height: 90px; max-width: 220px;" alt="Parent Signature">
                        <?php else: ?>
                            <div class="p-3 text-muted border border-dashed rounded bg-white small" style="max-height: 90px;">No signature uploaded</div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="row g-3 mt-3 border-top pt-3 text-start">
                    <div class="col-6"><small class="fw-bold text-secondary">Declaration Date:</small> <span class="small fw-semibold"><?= !empty($student['declaration_date']) ? formatDate($student['declaration_date']) : '-' ?></span></div>
                    <div class="col-6"><small class="fw-bold text-secondary">Declaration Place:</small> <span class="small fw-bold text-dark"><?= htmlspecialchars($student['declaration_place'] ?? '-') ?></span></div>
                </div>
            </div>

            <!-- TRAINING CREDENTIALS -->
            <div class="sect-title"><i class="fas fa-shield-halved"></i>Training & Board Credentials</div>
            <div class="info-grid">
                <div class="info-card"><div class="info-label">Authorized Training Center</div><div class="info-val"><?= htmlspecialchars($student['training_center'] ?? '-') ?></div></div>
                <div class="info-card"><div class="info-label">Examining Body</div><div class="info-val fw-bold text-primary"><?= htmlspecialchars($student['examining_body'] ?? 'INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION (New Delhi)') ?></div></div>
            </div>

        </div>
    </div>
</div>

</main>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
