<?php
require_once 'db_admin.php';
checkLogin();

// Fetch Centers with Voter Count
// We add a subquery to count voters for each center efficiently
$stmt = $conn->query("
    SELECT vc.*, 
    (SELECT COUNT(id) FROM voters WHERE Center_Id = vc.id) as total_voters 
    FROM vote_centers vc 
    ORDER BY ward ASC, area_name ASC
");
$centers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Center List</title>
    <style>
        body { font-family: 'Arial', sans-serif; padding: 20px; }
        table { width: 100%; border-collapse: collapse; background: white; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #006a4e; color: white; }
        tr:nth-child(even) { background-color: #f2f2f2; }
        .btn { padding: 5px 10px; background: #d9534f; color: white; text-decoration: none; border-radius: 4px; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="header">
        <h2>Vote Centers List</h2>
        <a href="logout.php" style="color:red">Logout</a>
    </div>

    <!-- 1. Add this button at the top of your dashboard -->
    <div class="header">
        <h2>Vote Centers List</h2>
        <div>
            <button id="start-bulk" style="padding:10px; background:#000; color:#fff; cursor:pointer;">Generate All PDFs Automatically</button>
            <a href="logout.php" style="color:red; margin-left:20px;">Logout</a>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Ward & Area</th>
                <th>Center Name</th>
                <th>PDFs</th>
            </tr>
        </thead>
        <tbody>
        <tbody>
            <?php foreach($centers as $c): ?>
            <tr>
                <td><?php echo $c['id']; ?></td>
                <td><?php echo $c['ward']; ?><br><?php echo $c['area_name']; ?></td>
                <td>
                    <?php echo $c['center_name']; ?> (<?php echo $c['gender']; ?>)
                    <br>
                    <small style="color:gray;">(Total: <?php echo $c['total_voters']; ?>)</small>
                </td>
                <td>
                    <?php 
                    $limit = 1000;
                    if ($c['total_voters'] > 0) {
                        $parts = ceil($c['total_voters'] / $limit);
                        for ($i = 1; $i <= $parts; $i++) {
                            $offset = ($i - 1) * $limit;
                            $btnStyle = "display:inline-block; padding:3px 8px; margin:2px; background:#006a4e; color:white; text-decoration:none; border-radius:3px; font-size:12px;";
                            
                            // Added class 'pdf-queue-btn' and 'data-url'
                            echo "<a href='generate_pdf.php?center_id={$c['id']}&offset={$offset}&limit={$limit}' 
                                     target='_blank' 
                                     class='pdf-queue-btn' 
                                     style='{$btnStyle}'>Part {$i}</a> ";
                        }
                    }
                    ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- 3. Add jQuery and the script at the bottom -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function() {
        
        let queue = [];
        let currentIndex = 0;

        $('#start-bulk').on('click', function() {
            // Collect all buttons into a queue array
            queue = $('.pdf-queue-btn').toArray();
            currentIndex = 0;
            
            if(queue.length === 0) return alert("No PDFs to generate.");
            
            $(this).prop('disabled', true).text('Processing... Do not close window.');
            processNext();
        });

        function processNext() {
            if (currentIndex >= queue.length) {
                $('#start-bulk').text('All PDFs Generated Successfully!');
                return;
            }

            let $btn = $(queue[currentIndex]);
            let url = $btn.attr('href');

            // Update UI to show processing
            $btn.css('background', '#f0ad4e').text('Loading...');

            // Run AJAX
            $.ajax({
                url: url,
                type: 'GET',
                success: function() {
                    // Success: Mark as done and move to next
                    $btn.css('background', '#5cb85c').text('Done');
                    currentIndex++;
                    processNext(); // RECURSION: Start the next one
                },
                error: function() {
                    // Error: Mark as failed and move to next anyway
                    $btn.css('background', '#d9534f').text('Error');
                    currentIndex++;
                    processNext();
                }
            });
        }
    });
    </script>
</body>
</html>