<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: index.php');
    exit();
}
require_once('../db.php');

$message = "";
$error = "";

// Handle Leave Status Update
if (isset($_GET['leave_status']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $st = trim($_GET['leave_status']);
    if (in_array($st, ['Approved', 'Rejected', 'Pending'])) {
        $stmt = $conn->prepare("UPDATE leave_applications SET status=? WHERE id=?");
        $stmt->bind_param("si", $st, $id);
        $stmt->execute();
        $message = "Leave application marked as {$st}!";
    }
}

// Handle Leave Delete
if (isset($_GET['delete_leave'])) {
    $id = intval($_GET['delete_leave']);
    $conn->query("DELETE FROM leave_applications WHERE id = $id");
    $message = "Leave application deleted successfully!";
}

// Handle TC Status Update
if (isset($_GET['tc_status']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $st = trim($_GET['tc_status']);
    if (in_array($st, ['Under Process', 'Approved & Ready', 'Issued', 'Rejected'])) {
        $stmt = $conn->prepare("UPDATE tc_applications SET status=? WHERE id=?");
        $stmt->bind_param("si", $st, $id);
        $stmt->execute();
        $message = "TC application status updated to {$st}!";
    }
}

// Handle TC Delete
if (isset($_GET['delete_tc'])) {
    $id = intval($_GET['delete_tc']);
    $conn->query("DELETE FROM tc_applications WHERE id = $id");
    $message = "TC application deleted successfully!";
}

// Handle Admission Delete
if (isset($_GET['delete_adm'])) {
    $id = intval($_GET['delete_adm']);
    $conn->query("DELETE FROM admission_enquiries WHERE id = $id");
    $message = "Admission enquiry deleted successfully!";
}

// Active Tab
$tab = $_GET['tab'] ?? 'leave';

// Fetch Counts
$pending_leaves = $conn->query("SELECT COUNT(*) as c FROM leave_applications WHERE status = 'Pending'")->fetch_assoc()['c'] ?? 0;
$total_leaves = $conn->query("SELECT COUNT(*) as c FROM leave_applications")->fetch_assoc()['c'] ?? 0;
$total_tc = $conn->query("SELECT COUNT(*) as c FROM tc_applications")->fetch_assoc()['c'] ?? 0;
$total_adm = $conn->query("SELECT COUNT(*) as c FROM admission_enquiries")->fetch_assoc()['c'] ?? 0;

// Fetch Data based on active tab
$leave_rows = $conn->query("SELECT * FROM leave_applications ORDER BY id DESC");
$tc_rows = $conn->query("SELECT * FROM tc_applications ORDER BY id DESC");
$adm_rows = $conn->query("SELECT * FROM admission_enquiries ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Applications Box | BSPS Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root { --primary: #0b3b60; --accent: #f5a623; --dark: #1e293b; }
        body { background: #f8fafc; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .sidebar { height: 100vh; width: 260px; position: fixed; background: var(--dark); color: #fff; padding-top: 20px; overflow-y: auto; }
        .sidebar a { color: rgba(255,255,255,0.7); text-decoration: none; padding: 13px 25px; display: block; transition: 0.3s; font-size: 14.5px; }
        .sidebar a:hover, .sidebar a.active { color: #fff; background: #0b3b60; border-left: 4px solid var(--accent); }
        .main-content { margin-left: 260px; padding: 35px; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 18px rgba(0,0,0,0.06); }
        .nav-pills .nav-link { color: #475569; font-weight: 600; border-radius: 8px; padding: 10px 20px; margin-right: 10px; background: #fff; border: 1px solid #e2e8f0; }
        .nav-pills .nav-link.active { background: #0b3b60; color: #fff; border-color: #0b3b60; }
        .badge-pending { background: #fef3c7; color: #92400e; font-weight: 700; }
        .badge-approved { background: #dcfce7; color: #166534; font-weight: 700; }
        .badge-rejected { background: #fee2e2; color: #991b1b; font-weight: 700; }
        .logout-btn { position: relative; margin-top: 40px; padding: 0 15px; }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="px-4 mb-4">
            <h4 class="fw-bold text-white mb-0">BSPS ADMIN</h4>
            <span class="small text-secondary">Control Panel</span>
        </div>
        <a href="dashboard.php"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="manage_applications.php" class="active"><i class="fas fa-envelope-open-text me-2"></i> Applications Box <?php if($pending_leaves > 0): ?><span class="badge bg-danger ms-1"><?php echo $pending_leaves; ?></span><?php endif; ?></a>
        <a href="manage_schools.php"><i class="fas fa-school me-2"></i> Our Schools (Campuses)</a>
        <a href="manage_leadership.php"><i class="fas fa-users-cog me-2"></i> Board Leadership</a>
        <a href="manage_director.php"><i class="fas fa-user-tie me-2"></i> Director's Desk</a>
        <a href="manage_events.php"><i class="fas fa-calendar-alt me-2"></i> Events Gallery</a>
        <a href="manage_important_sites.php"><i class="fas fa-globe me-2"></i> Important Sites</a>
        <a href="manage_slider.php"><i class="fas fa-images me-2"></i> Manage Slider</a>
        <a href="manage_gallery.php"><i class="fas fa-photo-video me-2"></i> Manage Gallery</a>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt me-2"></i> Visit Website</a>
        <div class="logout-btn">
            <a href="logout.php" class="btn btn-outline-danger w-100 text-start py-2"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
        </div>
    </div>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold text-dark mb-1">Student Applications Box</h2>
                <div class="text-muted">Review incoming student leave applications, TC requests, and online admissions in one place.</div>
            </div>
            <?php if($pending_leaves > 0): ?>
                <span class="badge bg-danger px-3 py-2 fs-6">
                    <i class="fas fa-bell me-1"></i> <?php echo $pending_leaves; ?> New Leave Application(s) Pending
                </span>
            <?php endif; ?>
        </div>

        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show"><?php echo $message; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- Nav Tabs -->
        <ul class="nav nav-pills mb-4">
            <li class="nav-item">
                <a class="nav-link <?php echo $tab === 'leave' ? 'active' : ''; ?>" href="manage_applications.php?tab=leave">
                    <i class="fas fa-calendar-times me-2"></i> Leave Applications (Chutti) 
                    <span class="badge bg-warning text-dark ms-1"><?php echo $total_leaves; ?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $tab === 'tc' ? 'active' : ''; ?>" href="manage_applications.php?tab=tc">
                    <i class="fas fa-file-contract me-2"></i> TC Requests 
                    <span class="badge bg-secondary ms-1"><?php echo $total_tc; ?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $tab === 'adm' ? 'active' : ''; ?>" href="manage_applications.php?tab=adm">
                    <i class="fas fa-user-graduate me-2"></i> Admission Enquiries 
                    <span class="badge bg-secondary ms-1"><?php echo $total_adm; ?></span>
                </a>
            </li>
        </ul>

        <!-- TAB 1: Leave Applications -->
        <?php if ($tab === 'leave'): ?>
        <div class="card p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="fw-bold text-dark mb-0"><i class="fas fa-envelope text-primary me-2"></i> Student Leave Applications (Chutti ki Application)</h5>
                <span class="small text-muted">Total: <?php echo $total_leaves; ?> records</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>App No &amp; Date</th>
                            <th>Student &amp; Father Name</th>
                            <th>School &amp; Class</th>
                            <th>Leave Period</th>
                            <th>Reason for Leave</th>
                            <th>Parent Contact</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($leave_rows && $leave_rows->num_rows > 0): ?>
                            <?php while ($row = $leave_rows->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <span class="badge bg-light text-dark border fw-bold"><?php echo htmlspecialchars($row['app_no']); ?></span>
                                        <div class="text-muted small mt-1"><?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-dark"><?php echo htmlspecialchars($row['student_name']); ?></div>
                                        <div class="text-muted small">S/O: <?php echo htmlspecialchars($row['father_name']); ?></div>
                                    </td>
                                    <td>
                                        <span class="badge bg-info text-dark"><?php echo htmlspecialchars($row['school_name']); ?></span>
                                        <div class="fw-semibold small mt-1">Class: <?php echo htmlspecialchars($row['class_name']); ?> <?php echo $row['section'] ? '('.htmlspecialchars($row['section']).')' : ''; ?></div>
                                    </td>
                                    <td>
                                        <div class="small fw-bold text-primary">
                                            <?php echo date('d M', strtotime($row['from_date'])); ?> &rarr; <?php echo date('d M Y', strtotime($row['to_date'])); ?>
                                        </div>
                                        <span class="badge bg-secondary small"><?php echo $row['total_days']; ?> Day(s)</span>
                                    </td>
                                    <td>
                                        <span class="badge bg-warning text-dark"><?php echo htmlspecialchars($row['reason_type']); ?></span>
                                        <?php if ($row['reason_details']): ?>
                                            <div class="small text-muted text-truncate mt-1" style="max-width: 200px;" title="<?php echo htmlspecialchars($row['reason_details']); ?>">
                                                <?php echo htmlspecialchars($row['reason_details']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="tel:<?php echo htmlspecialchars($row['parent_mobile']); ?>" class="text-decoration-none fw-semibold">
                                            <i class="fas fa-phone-alt text-success me-1"></i> <?php echo htmlspecialchars($row['parent_mobile']); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <?php if ($row['status'] === 'Approved'): ?>
                                            <span class="badge badge-approved px-2.5 py-1.5"><i class="fas fa-check-circle me-1"></i> Approved</span>
                                        <?php elseif ($row['status'] === 'Rejected'): ?>
                                            <span class="badge badge-rejected px-2.5 py-1.5"><i class="fas fa-times-circle me-1"></i> Rejected</span>
                                        <?php else: ?>
                                            <span class="badge badge-pending px-2.5 py-1.5"><i class="fas fa-clock me-1"></i> Pending</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $wa_text = urlencode(
                                            "🏫 *BSPS & AHIS - STUDENT LEAVE NOTICE*\n"
                                          . "━━━━━━━━━━━━━━━━━━━━\n"
                                          . "🆔 *App No:* {$row['app_no']}\n"
                                          . "👤 *Student:* {$row['student_name']}\n"
                                          . "👨‍👦 *Father:* {$row['father_name']}\n"
                                          . "🏫 *School:* {$row['school_name']}\n"
                                          . "📚 *Class:* {$row['class_name']}\n"
                                          . "📅 *Dates:* " . date('d M', strtotime($row['from_date'])) . " to " . date('d M Y', strtotime($row['to_date'])) . " ({$row['total_days']} Days)\n"
                                          . "📝 *Reason:* {$row['reason_type']}\n"
                                          . ($row['reason_details'] ? "💬 *Details:* {$row['reason_details']}\n" : "")
                                          . "📞 *Mobile:* {$row['parent_mobile']}\n"
                                          . "━━━━━━━━━━━━━━━━━━━━\n"
                                          . "✅ *Status:* {$row['status']}"
                                        );
                                        ?>
                                        <div class="d-flex gap-1">
                                            <a href="https://api.whatsapp.com/send?text=<?php echo $wa_text; ?>" target="_blank" class="btn btn-sm btn-success" title="Forward to WhatsApp Group">
                                                <i class="fab fa-whatsapp"></i>
                                            </a>
                                            <?php if ($row['status'] !== 'Approved'): ?>
                                                <a href="manage_applications.php?tab=leave&leave_status=Approved&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-success" title="Approve Leave">
                                                    <i class="fas fa-check"></i>
                                                </a>
                                            <?php endif; ?>
                                            <?php if ($row['status'] !== 'Rejected'): ?>
                                                <a href="manage_applications.php?tab=leave&leave_status=Rejected&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-warning" title="Reject Leave">
                                                    <i class="fas fa-times"></i>
                                                </a>
                                            <?php endif; ?>
                                            <a href="manage_applications.php?tab=leave&delete_leave=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this leave application?')" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="text-center py-4 text-muted">
                                    <i class="fas fa-inbox fs-2 d-block mb-2 text-secondary"></i>
                                    Abhi koi chutti ki application praapt nahi hui hai. Student application submit karte hi yahan show hogi.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- TAB 2: TC Applications -->
        <?php if ($tab === 'tc'): ?>
        <div class="card p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="fw-bold text-dark mb-0"><i class="fas fa-file-contract text-primary me-2"></i> Transfer Certificate (TC) Requests</h5>
                <span class="small text-muted">Total: <?php echo $total_tc; ?> records</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>App No &amp; Date</th>
                            <th>Student &amp; Father Name</th>
                            <th>School &amp; Class</th>
                            <th>Scholar/Admn No</th>
                            <th>Reason for TC</th>
                            <th>Contact</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($tc_rows && $tc_rows->num_rows > 0): ?>
                            <?php while ($row = $tc_rows->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <span class="badge bg-light text-dark border fw-bold"><?php echo htmlspecialchars($row['app_no']); ?></span>
                                        <div class="text-muted small mt-1"><?php echo date('d M Y', strtotime($row['created_at'])); ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-dark"><?php echo htmlspecialchars($row['student_name']); ?></div>
                                        <div class="text-muted small">S/O: <?php echo htmlspecialchars($row['father_name']); ?></div>
                                    </td>
                                    <td>
                                        <span class="badge bg-info text-dark"><?php echo htmlspecialchars($row['school_name']); ?></span>
                                        <div class="small mt-1">Class: <?php echo htmlspecialchars($row['class_name']); ?></div>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary"><?php echo htmlspecialchars($row['scholar_no'] ?: 'N/A'); ?></span>
                                    </td>
                                    <td>
                                        <div class="small text-muted text-truncate" style="max-width: 250px;" title="<?php echo htmlspecialchars($row['reason_for_leaving']); ?>">
                                            <?php echo htmlspecialchars($row['reason_for_leaving']); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <a href="tel:<?php echo htmlspecialchars($row['parent_mobile']); ?>" class="text-decoration-none">
                                            <i class="fas fa-phone-alt text-success me-1"></i> <?php echo htmlspecialchars($row['parent_mobile']); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary"><?php echo htmlspecialchars($row['status']); ?></span>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="manage_applications.php?tab=tc&tc_status=Approved & Ready&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-success" title="Mark Ready">
                                                <i class="fas fa-check"></i>
                                            </a>
                                            <a href="manage_applications.php?tab=tc&tc_status=Issued&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-primary" title="Mark Issued">
                                                <i class="fas fa-stamp"></i>
                                            </a>
                                            <a href="manage_applications.php?tab=tc&delete_tc=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this TC request?')" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="text-center py-4 text-muted">No TC applications submitted yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- TAB 3: Admission Enquiries -->
        <?php if ($tab === 'adm'): ?>
        <div class="card p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="fw-bold text-dark mb-0"><i class="fas fa-user-graduate text-primary me-2"></i> Online Admission Enquiries</h5>
                <span class="small text-muted">Total: <?php echo $total_adm; ?> records</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Student Name</th>
                            <th>Parent Name</th>
                            <th>Grade/Class</th>
                            <th>Contact Info</th>
                            <th>Address</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($adm_rows && $adm_rows->num_rows > 0): ?>
                            <?php while ($row = $adm_rows->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($row['created_at'])); ?></td>
                                    <td class="fw-bold text-dark"><?php echo htmlspecialchars($row['student_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['parent_name']); ?></td>
                                    <td><span class="badge bg-warning text-dark"><?php echo htmlspecialchars($row['grade']); ?></span></td>
                                    <td>
                                        <a href="tel:<?php echo htmlspecialchars($row['phone']); ?>" class="text-decoration-none d-block">
                                            <i class="fas fa-phone-alt text-success me-1"></i> <?php echo htmlspecialchars($row['phone']); ?>
                                        </a>
                                        <?php if($row['email']): ?>
                                            <small class="text-muted"><?php echo htmlspecialchars($row['email']); ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><small class="text-muted"><?php echo htmlspecialchars($row['address']); ?></small></td>
                                    <td>
                                        <a href="manage_applications.php?tab=adm&delete_adm=<?php echo $row['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this enquiry?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center py-4 text-muted">No admission enquiries recorded yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

    </div>

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