<?php
session_start();
require '../backend/connection.php'; // Adjust path if needed

// Get the current date
date_default_timezone_set('Asia/Kuala_Lumpur'); // Set timezone to GMT+8
$current_date = date('Y-m-d'); // Get current date and time in GMT+8
$masjid_id = $_SESSION['masjid_id'];

// Query to check if a booking exists for today
$sql = "SELECT * FROM booking b 
JOIN user u ON b.user_id = u.user_id
JOIN masjid m ON u.masjid_id = m.masjid_id 
WHERE m.masjid_id = :masjid_id AND b.status_code = 1 ";

$stmt = $conn->prepare($sql);
$stmt->execute([
    'masjid_id' => $masjid_id
]);

$booking = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$booking) {
    header("Location: mainpage.php");
    exit();
}

try {
    // Fetch top 8 male candidates with the highest total_vote from `form`
    $queryMale = "SELECT f.*, u.*, m.*
        FROM form f 
        JOIN sej6x_data_peribadi u ON u.no_ic = f.ic
        JOIN masjid m ON u.id_masjid = m.masjid_id
        WHERE m.masjid_id = :masjid_id AND DATE(f.date) = :current_date AND u.jantina = 1
        ORDER BY f.total_vote DESC
        LIMIT 8";

    $stmtMale = $conn->prepare($queryMale);
    $stmtMale->execute([
        'masjid_id' => $masjid_id,
        'current_date' => $current_date
    ]);

    $topMaleCandidates = $stmtMale->fetchAll(PDO::FETCH_ASSOC);

    // Fetch top 2 female candidates with the highest total_vote from `form`
    $queryFemale = "SELECT f.*, u.*, m.*
        FROM form f 
        JOIN sej6x_data_peribadi u ON u.no_ic = f.ic
        JOIN masjid m ON u.id_masjid = m.masjid_id
        WHERE m.masjid_id = :masjid_id AND DATE(f.date) = :current_date AND u.jantina = 2
        ORDER BY f.total_vote DESC
        LIMIT 2";

    $stmtFemale = $conn->prepare($queryFemale);
    $stmtFemale->execute([
        'masjid_id' => $masjid_id,
        'current_date' => $current_date
    ]);

    $topFemaleCandidates = $stmtFemale->fetchAll(PDO::FETCH_ASSOC);

    // Combine the results
    $topCandidates = array_merge($topMaleCandidates, $topFemaleCandidates);

} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// Handle form submission to save data into `form2`
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_to_form2'])) {
    try {
        $conn->beginTransaction(); // Start DB transaction

        // Insert top candidates into `form2`
        foreach ($topCandidates as $candidate) {
            $stmtInsert = $conn->prepare("
                INSERT INTO form_2 (masjid_id, ic, name, gender, date, phone_num, address, job, total_vote, status_code, booking_id)
                VALUES (:masjid_id, :ic, :name, :gender, :date, :phone_num, :address, :job, :total_vote, :status_code, :booking_id)
            ");
            $stmtInsert->execute([
                ':masjid_id' => $candidate['masjid_id'],
                ':ic' => $candidate['ic'],
                ':name' => $candidate['name'],
                ':gender' => $candidate['gender'],
                ':date' => $candidate['date'],
                ':phone_num' => $candidate['phone_num'],
                ':address' => $candidate['address'],
                ':job' => $candidate['job'],
                ':total_vote' => $candidate['total_vote'],
                ':status_code' => 2, 
                ':booking_id' => $booking['booking_id']
            ]);
        }

        // Update booking status to 'tindakan_code' = 2
        $tindakan_code = 2;
        $status_code = 4;
        $stmt = $conn->prepare("
            UPDATE booking 
            SET tindakan_code = :tindakan_code, status_code = :status_code
            WHERE booking_id = :booking_id
        ");
        $stmt->execute([
            ':booking_id' => $booking['booking_id'],
            ':tindakan_code' => 2,
            ':status_code' => 4
        ]);

        $conn->commit(); // Commit transaction
        $_SESSION['message'] = "DATA BERJAYA DISIMPAN!";
        header("Location: mainpage.php"); // Redirect to the same page
        exit();
    } catch (PDOException $e) {
        $conn->rollBack(); // Rollback on error
        $_SESSION['error'] = "Error saving data to `form2`: " . $e->getMessage();
        header("Location: mainpage.php"); // Redirect to the same page
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BORANG PENCALONAN 2 - VIEW</title>
    <script type="text/javascript" src="../Script/ajax.js"></script>
    <link rel="stylesheet" href="../css/styles.css"> <!-- Adjust path if needed -->
    <!-- Add SweetAlert CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
</head>
<body>
<?php require '../include/header.php'; ?>

<!-- Show Alert Message (if any) -->
<?php
if (isset($_SESSION['message'])) {
    echo "<script>alert('" . $_SESSION['message'] . "');</script>";
    unset($_SESSION['message']); // Clear the message after displaying
}

if (isset($_SESSION['error'])) {
    echo "<script>alert('" . $_SESSION['error'] . "');</script>";
    unset($_SESSION['error']); // Clear the error after displaying
}
?>

<div class="container">
    <h2 class="text-center">SENARAI CALON - BORANG PENCALONAN 2</h2>
    <h2 class="text-center">CALON-CALON TERPILIH:</h2>
    <div class="table-responsive">
        <table class="table table-bordered text-center">
            <thead class="table-primary text-white">
                <tr>
                    <th>NO.</th>
                    <th>NAMA</th>
                    <th>JANTINA</th>
                    <th>NO KAD PENGENALAN</th>
                    <th>NO TELEFON</th>
                    <th>ALAMAT</th>
                    <th>PEKERJAAN</th>
                    <th>JUMLAH UNDI</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($topCandidates)): ?>
                    <tr><td colspan="7">TIADA DATA DIJUMPAI.</td></tr>
                <?php else: ?>
                    <?php 
                        $counter = 1;
                        foreach ($topCandidates as $candidate): ?>
                        <tr>
                            <td><?php echo $counter++; ?></td>
                            <td><?php echo htmlspecialchars($candidate['name']); ?></td>
                            <td>
                                <?php
                                $genderId = $candidate['gender'];
                                if ($genderId == 1) {
                                    echo 'LELAKI';
                                } elseif ($genderId == 2) {
                                    echo 'PEREMPUAN';
                                }
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($candidate['ic']); ?></td>
                            <td><?php echo htmlspecialchars($candidate['phone_num']); ?></td>
                            <td><?php echo htmlspecialchars($candidate['address']); ?></td>
                            <td><?php echo htmlspecialchars($candidate['job']); ?></td>
                            <td><?php echo htmlspecialchars($candidate['total_vote']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Form to submit data to `form2` -->
    <form method="POST" action="" id="submitForm">
        <div class="text-center mt-4">
            <button type="button" name="submit_to_form2" class="btn btn-success" id="submitButton">HANTAR</button>
        </div>
    </form>
</div>

<?php require '../include/footer.php'; ?>

<!-- Add SweetAlert JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const submitButton = document.getElementById('submitButton');
        const submitForm = document.getElementById('submitForm');
        
        submitButton.addEventListener('click', function(e) {
            e.preventDefault();
            
            Swal.fire({
                title: 'ADAKAH ANDA PASTI?',
                text: "BORANG PENCALONAN 2 AKAN DIHANTAR KE PEJABAT AGAMA DAERAH.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'YA, HANTAR!',
                cancelButtonText: 'BATAL'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Create a hidden submit button and click it
                    const hiddenSubmit = document.createElement('input');
                    hiddenSubmit.type = 'submit';
                    hiddenSubmit.name = 'submit_to_form2';
                    hiddenSubmit.style.display = 'none';
                    submitForm.appendChild(hiddenSubmit);
                    hiddenSubmit.click();
                }
            });
        });
    });
</script>
</body>
</html>