<?php
session_start();
if (!isset($_SESSION["admin_logged_in"])) {
    header("Location: admin_login.php");
    exit();
}

$conn = new mysqli("localhost", "root", "", "spiritan_admissions");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Include PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

// Send notification email function
function sendNotification($to, $name, $form_number, $status, &$errorMsg = '') {
    $mail = new PHPMailer(true);
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'mail.spiritan-edu.org'; // Change to your SMTP host
        $mail->SMTPAuth = true;
        $mail->Username = 'info@spiritan-edu.org'; // Change to your SMTP username
        $mail->Password = 'spiritan@2025'; // Change to your SMTP password
        $mail->SMTPSecure = 'ssl'; // 'ssl' or 'tls'
        $mail->Port = 465; // 465 for ssl, 587 for tls

        // Recipients
        $mail->setFrom('info@spiritan-edu.org', 'SIGSS Admissions');
        $mail->addAddress($to, $name);

        // Email content
        if ($status === 'Approved') {
            $mail->Subject = 'Congratulations! Your SIGSS Admission Form Has Been Approved';
            $mail->Body = "Dear $name,\n\nWe are pleased to inform you that your application with Form Number: $form_number has been approved.\n\nFurther details will follow.\n\nBest regards,\nSpiritan International Girls' Secondary School";
        } else {
            $mail->Subject = 'Update on Your SIGSS Admission Application';
            $mail->Body = "Dear $name,\n\nWe regret to inform you that your application with Form Number: $form_number was not successful.\n\nThank you for your interest.\n\nSincerely,\nSpiritan International Girls' Secondary School";
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        $errorMsg = $mail->ErrorInfo;
        return false;
    }
}

// Handle test email sending
/*if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_recent_notifications'])) {
    // Fetch recent applicants, you can change limit as needed
    $query = "SELECT full_name, email, form_number, status 
              FROM applications 
              WHERE email IS NOT NULL AND email != '' 
              ORDER BY created_at DESC 
              LIMIT 10";

    $result = $conn->query($query);

    $successCount = 0;
    $failures = [];

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $name = $row['full_name'];
            $email = $row['email'];
            $formNum = $row['form_number'];
            $status = $row['status'] ?? 'Pending'; // or use whatever status you want to send notification about

            $errorMsg = '';
            $sent = sendNotification($email, $name, $formNum, $status, $errorMsg);

            if ($sent) {
                $successCount++;
            } else {
                $failures[] = "Failed for $email: " . htmlspecialchars($errorMsg);
            }
        }
    } else {
        $_SESSION['email_error'] = "No recent applicants found to notify.";
    }

    if ($successCount > 0) {
        $_SESSION['email_success'] = "Notification emails sent to $successCount recent applicant(s).";
    }

    if (!empty($failures)) {
        $_SESSION['email_error'] = implode('<br>', $failures);
    }

    header("Location: dashboard.php");
    exit();
}
*/

// Handle approve/disapprove and send notification
if (isset($_GET['action']) && isset($_GET['id'])) {
    $status = $_GET['action'] === 'approve' ? 'Approved' : 'Disapproved';

    $stmt = $conn->prepare("UPDATE applications SET status=? WHERE id=?");
    $stmt->bind_param("si", $status, $_GET['id']);
    $stmt->execute();

    $id = (int)$_GET['id'];
    $result = $conn->query("SELECT full_name, email, form_number FROM applications WHERE id=$id");
    if ($result && $row = $result->fetch_assoc()) {
        $errorMsg = '';
        $emailSent = sendNotification($row['email'], $row['full_name'], $row['form_number'], $status, $errorMsg);
        if (!$emailSent) {
            $_SESSION['email_error'] = "Email sending failed: " . htmlspecialchars($errorMsg);
        } else {
            $_SESSION['email_success'] = "Notification email sent successfully.";
        }
    }

    header("Location: dashboard.php");
    exit();
}

// Fetch application data according to filter
$filter = $_GET['filter'] ?? 'all';
switch ($filter) {
    case 'approved':
        $applications = $conn->query("SELECT * FROM applications WHERE status='Approved' ORDER BY id DESC");
        break;
    case 'disapproved':
        $applications = $conn->query("SELECT * FROM applications WHERE status='Disapproved' ORDER BY id DESC");
        break;
    default:
        $applications = $conn->query("SELECT * FROM applications ORDER BY id DESC");
        break;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #eef2f5;
            padding: 30px;
        }
        h2 {
            text-align: center;
        }
        .filter-print {
            text-align: center;
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.05);
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            font-size: 14px;
            text-align: center;
        }
        th {
            background: #007bff;
            color: white;
        }
        a {
            color: #007bff;
            text-decoration: none;
        }
        .btn {
            padding: 5px 10px;
            border-radius: 4px;
            background: #28a745;
            color: white;
            margin: 2px;
            text-decoration: none;
            cursor: pointer;
            border: none;
        }
        .btn.disapprove {
            background: #dc3545;
        }
        .btn.print {
            background: #6c757d;
        }
        .btn.test-email {
            background: #17a2b8;
            margin-bottom: 15px;
        }
        .status {
            font-weight: bold;
        }
        .message {
            margin: 15px 0;
            text-align: center;
            font-weight: bold;
            font-size: 16px;
        }
        .message.success {
            color: green;
        }
        .message.error {
            color: red;
        }
    </style>
</head>
<body>

    <h2>SIGSS Applications Dashboard</h2>

    <!-- Show success/error messages -->
    <?php if (isset($_SESSION['email_error'])): ?>
        <div class="message error"><?= $_SESSION['email_error'] ?></div>
        <?php unset($_SESSION['email_error']); ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['email_success'])): ?>
        <div class="message success"><?= $_SESSION['email_success'] ?></div>
        <?php unset($_SESSION['email_success']); ?>
    <?php endif; ?>

    <!-- Test Email Button -->
   

    <div class="filter-print">
        <form method="get" style="display:inline-block;">
            <label for="filter">Filter:</label>
            <select name="filter" id="filter" onchange="this.form.submit()">
                <option value="all" <?= $filter === 'all' ? 'selected' : '' ?>>All</option>
                <option value="approved" <?= $filter === 'approved' ? 'selected' : '' ?>>Approved</option>
                <option value="disapproved" <?= $filter === 'disapproved' ? 'selected' : '' ?>>Disapproved</option>
            </select>
        </form>
        <button onclick="window.print()" class="btn print">🖨️ Print List</button>
    </div>

    <table>
        <tr>
            <th>Form No</th>
            <th>Name</th>
            <th>Email</th>
            <th>Class</th>
            <th>Passport</th>
            <th>Receipt</th>
            <th>Date</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
        <?php while ($row = $applications->fetch_assoc()): ?>
        <tr>
            <td><?= htmlspecialchars($row["form_number"]) ?></td>
            <td><?= htmlspecialchars($row["full_name"]) ?></td>
            <td><?= htmlspecialchars($row["email"]) ?></td>
            <td><?= htmlspecialchars($row["class_intended"]) ?></td>
            <td>
                <?= !empty($row['passport_path']) 
                    ? "<a href='" . htmlspecialchars($row['passport_path']) . "' target='_blank'>View</a>" 
                    : "<span class='text-muted'>Not Uploaded</span>"; ?>
            </td>
            <td>
                <?= !empty($row['receipt_path']) && file_exists($row['receipt_path']) 
                    ? "<a href='" . htmlspecialchars($row['receipt_path']) . "' target='_blank'>View</a>" 
                    : "<span class='text-muted'>Not Uploaded</span>"; ?>
            </td>
            <td><?= htmlspecialchars($row["created_at"]) ?></td>
            <td class="status"><?= htmlspecialchars($row["status"] ?? "Pending") ?></td>
            <td>
                <a class="btn" href="?action=approve&id=<?= $row['id'] ?>" onclick="return confirm('Approve this application?');">Approve</a>
                <a class="btn disapprove" href="?action=disapprove&id=<?= $row['id'] ?>" onclick="return confirm('Disapprove this application?');">Disapprove</a>
            </td>
        </tr>
        <?php endwhile; ?>
    </table>

</body>
</html>
