<?php 
session_start();

if (!isset($_SESSION['login'])) {
    header('location:login');
    exit;
}

$_SESSION['role'];
require 'function.php';
require 'config.php';

if (!is_subscription_active($_SESSION['id'])) {
    header('location:profile.php?info=expired');
    exit;
}

include_once 'reset.php';

$active_event_id = get_active_event_id();
$comment_id = [];
$link_undangan = '';
if ($active_event_id) {
    $comment_id = query("SELECT * FROM comment_id WHERE event_id = '$active_event_id' ORDER BY no_id DESC");
    
    // Check and auto-migrate link_undangan & text_wa if they don't exist
    $check_col = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'link_undangan'");
    if(mysqli_num_rows($check_col) == 0) {
        mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `link_undangan` VARCHAR(255) NULL AFTER `acara`");
    }
    $check_col2 = mysqli_query($koneksi, "SHOW COLUMNS FROM `event_id` LIKE 'text_wa'");
    if(mysqli_num_rows($check_col2) == 0) {
        mysqli_query($koneksi, "ALTER TABLE `event_id` ADD `text_wa` TEXT NULL AFTER `link_undangan`");
    }
    
    $check_col3 = mysqli_query($koneksi, "SHOW COLUMNS FROM `comment_id` LIKE 'jumlah_tamu'");
    if(mysqli_num_rows($check_col3) == 0) {
        mysqli_query($koneksi, "ALTER TABLE `comment_id` ADD `jumlah_tamu` INT NOT NULL DEFAULT '1' AFTER `tamu`");
    }
    
    $ev_res = mysqli_query($koneksi, "SELECT link_undangan, text_wa FROM event_id WHERE id = '$active_event_id'");
    if ($ev_res) {
        $ev_data = mysqli_fetch_assoc($ev_res);
        $link_undangan = $ev_data['link_undangan'] ?? '';
    }
}

$user_id = $_SESSION['id'];
$result = mysqli_query($koneksi, "SELECT * FROM users_id WHERE id = '$user_id'");
$whatsapp = mysqli_fetch_assoc($result);

// Fetch admin's template for fallback
$admin_res = mysqli_query($koneksi, "SELECT whatsapp FROM users_id WHERE role = 'admin' LIMIT 1");
$admin_data = $admin_res ? mysqli_fetch_assoc($admin_res) : null;

// Pull specific event template if exists, otherwise fallback to global admin template
$fallback_text = "Terima kasih banyak atas kehadiran Bapak/Ibu/Saudara/i [nama] di Hari Bahagia Kami, pada hari [tgl] jam [jam].\nTerima kasih atas doa restu terbaik yang Anda berikan kepada Kami dan Keluarga.";
$pesan = (!empty($ev_data['text_wa'])) ? $ev_data['text_wa'] : (!empty($admin_data['whatsapp']) ? $admin_data['whatsapp'] : $fallback_text);

$user_role = $whatsapp['role'] ?? '';
$notifwa = $whatsapp['starsender'] ?? '';

$apikey = $whatsapp['apikey'] ?? '';

$cat = get_cat();

if (isset($_POST['simpan'])) {
    $result = tambah($_POST);
    if ($result) {
        // redirect( "/dashboard" ); 
        echo "<script>
                // alert('Daftar tamu berhasil ditambahkan!');
                window.location.href='/dashboard';
            </script>";
    } else {
         echo "<script>
                alert('Daftar tamu gagal ditambahkan!');
            </script>";
    }
}
require 'header.php';
?>

    <!-- Main Container -->
    <div class="container pb-5">
        
        <!-- Header Section -->
        <div class="row mb-4 mt-5">
            <div class="col-md-12 text-center text-md-start">
                <h2 class="fw-bold text-gradient d-inline-block"><?= $acara ?></h2>
                <p class="text-muted small">Manage guest list for this event.</p>
            </div>
        </div>

        <!-- Glass Card for Content -->
        <div class="glass-card">
            
            <!-- Toolbar Desktop (md and above) -->
            <div class="d-none d-md-flex flex-wrap gap-2 mb-4 justify-content-between align-items-center">
                <div class="d-flex flex-wrap gap-2">
                    <a href="welcome?event_id=<?= $active_event_id ?>" target="_blank" class="btn btn-secondary btn-sm">
                        <i class="bi bi-display"></i> Welcome
                    </a>
                    <a href="gethering?event_id=<?= $active_event_id ?>" target="_blank" class="btn btn-secondary btn-sm">
                        <i class="bi bi-people"></i> Gathering
                    </a>
                    <button type="button" id="scan-qr-code" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#Scan">
                        <i class="bi bi-qr-code-scan"></i> Scan QR
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#AddData">
                        <i class="bi bi-plus-lg"></i> Tambah Tamu
                    </button>
                </div>
                
                <div class="d-flex flex-wrap gap-2">
                    <button type="button" id="import" class="btn btn-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#Import">
                        <i class="bi bi-upload"></i> Import Data
                    </button>
                    <a href="export" target="_blank" class="btn btn-secondary btn-sm"><i class="bi bi-file-earmark-excel"></i> Export Excel</a>
                    <a href="print" target="_blank" class="btn btn-secondary btn-sm"><i class="bi bi-file-earmark-pdf"></i> Export PDF</a>
                </div>
            </div>

            <!-- Toolbar Mobile (under md) -->
            <div class="d-md-none mb-4">
                <div class="row g-2 mb-2">
                    <div class="col-6">
                        <a href="welcome?event_id=<?= $active_event_id ?>" target="_blank" class="btn btn-secondary btn-sm w-100 py-2">
                            <i class="bi bi-display"></i> Welcome
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="gethering?event_id=<?= $active_event_id ?>" target="_blank" class="btn btn-secondary btn-sm w-100 py-2">
                            <i class="bi bi-people"></i> Gathering
                        </a>
                    </div>
                </div>
                <div class="row g-2 mb-2">
                    <div class="col-6">
                        <button type="button" class="btn btn-primary btn-sm w-100 py-2" data-bs-toggle="modal" data-bs-target="#Scan">
                            <i class="bi bi-qr-code-scan"></i> Scan QR
                        </button>
                    </div>
                    <div class="col-6">
                        <button type="button" class="btn btn-primary btn-sm w-100 py-2" data-bs-toggle="modal" data-bs-target="#AddData">
                            <i class="bi bi-plus-lg"></i> Tambah Tamu
                        </button>
                    </div>
                </div>
                <div class="row g-2">
                    <div class="col-4">
                        <button type="button" class="btn btn-secondary btn-xs w-100 py-2 px-0" style="font-size: 11px;" data-bs-toggle="modal" data-bs-target="#Import">
                            <i class="bi bi-upload"></i> Import Data
                        </button>
                    </div>
                    <div class="col-4">
                        <a href="export" target="_blank" class="btn btn-secondary w-100 py-2 px-0" style="font-size: 11px;">
                            <i class="bi bi-file-earmark-excel"></i> Export Excel
                        </a>
                    </div>
                    <div class="col-4">
                        <a href="print" target="_blank" class="btn btn-secondary w-100 py-2 px-0" style="font-size: 11px;">
                            <i class="bi bi-file-earmark-pdf"></i> Export PDF
                        </a>
                    </div>
                </div>
            </div>

            <!-- Messages -->
            <?php if(!empty($statusMsgok)){ ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo $statusMsgok; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php }elseif(!empty($statusMsgerror)){ ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $statusMsgerror; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php } ?>

            <!-- Table -->
            <div class="table-responsive">
                <form id="example" name="bulk_action_form" action="" method="post">
                    <table id="data" class="table table-hover align-middle mb-0" style="width:100%;">
                        <thead>
                            <tr>
                                <th class="text-center">No</th>
                                <th class="text-center">Pilih</th>
                                <th>Nama</th>
                                <th>Waktu Hadir</th>
                                <th>Kategori</th>
                                <th class="text-center">Jumlah</th>
                                <th>WA</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no=1; $count = 0; ?>
                            <?php foreach ($comment_id as $row) : 
                                $count++;
                                $date = $row['jam'];
                                $pesanwa = strip_tags($pesan);
                                $pesanwa = str_replace('[nama]',$row['nama'],$pesanwa);
                                
                                if (!empty($link_undangan)) {
                                    $pesanwa = str_replace('[link-undangan]', $link_undangan . str_replace(' ', '+', $row['nama']), $pesanwa);
                                } else {
                                    $pesanwa = str_replace('[link-undangan]', '', $pesanwa);
                                }
                                
                                $pesanwa = str_replace('[tgl]',$row['tgl'],$pesanwa);
                                $pesanwa = str_replace('[jam]',$date,$pesanwa);
                            ?>
                            <tr class="guest-row">
                                <td class="text-center align-middle" data-label="No"><?= sprintf("%02d", $no++); ?></td>
                                <td class="text-center align-middle" data-label="Checkbox">
                                    <input type="checkbox" value="<?php echo $row['no_id']; ?>" id="checked_id[]" name="checked_id[]" class="single_select checkbox form-check-input" data-wa="<?=$row['whatsapp']; ?>" data-pesan="<?=$pesanwa; ?>" />
                                </td>
                                <td class="fw-bold align-middle" data-label="Nama"><?= $row['nama']; ?></td>
                                <td class="align-middle" data-label="Waktu Hadir"><span style="font-size:0.85em;"><?= $row['tgl']; ?> <span class="text-muted">• <?= date("H:i", strtotime($date));?></span></span></td>
                                
                                <td class="d-md-none mobile-collapse-row" data-bs-toggle="collapse" data-bs-target=".details-<?= $row['no_id']; ?>">
                                    <i class="bi bi-chevron-down"></i> <small class="fw-bold ms-1">Info Lainnya</small>
                                </td>
                                
                                <td class="align-middle collapse d-md-table-cell details-<?= $row['no_id']; ?>" data-label="Kategori"><span class="badge bg-secondary rounded-pill"><?= $row['tamu']; ?></span></td>
                                <td class="text-center align-middle collapse d-md-table-cell details-<?= $row['no_id']; ?>" data-label="Jumlah"><?= isset($row['jumlah_tamu']) ? $row['jumlah_tamu'] : '1'; ?></td>
                                <td class="align-middle collapse d-md-table-cell details-<?= $row['no_id']; ?>" data-label="WA"><?php echo $row['whatsapp']; ?></td>
                                <td class="text-center align-middle" data-label="Action">
                                    <div class="d-flex gap-1 justify-content-center">
                                        <a href="https://api.whatsapp.com/send?phone=<?php echo $row['whatsapp'];?>&text=<?php echo rawurlencode($pesanwa);?>" target="_blank" class="btn btn-outline-success btn-sm p-1 px-2" title="WhatsApp"><i class="bi bi-whatsapp"></i></a>
                                        <a href="/manual?name=<?php echo $row['nama'];?>" target="_blank" class="btn btn-outline-info btn-sm p-1 px-2" title="Welcome"><i class="bi bi-display"></i></a>
                                        <button type="button" class="btn btn-outline-warning btn-sm p-1 px-2" data-bs-toggle="modal" data-bs-target="#update_modal<?php echo $row['no_id']; ?>" title="Edit"><i class="bi bi-pencil"></i></button>
                                        <?php if ($user_role == 'admin' || $user_role == 'member') : ?>
                                            <a href="hapus?no_id=<?= $row['no_id']; ?>" class="btn btn-outline-danger btn-sm p-1 px-2" onclick="return confirm('Delete <?= $row['nama']; ?>?');" title="Delete"><i class="bi bi-trash"></i></a>
                                        <?php endif;?>
                                    </div>
                                 </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <div class="mt-4 p-4 border-top">
                        <div class="d-flex flex-wrap gap-2 align-items-center">
                            <span class="text-muted small fw-bold me-2"><i class="bi bi-lightning-fill"></i> BULK:</span>
                            <button type="button" class="btn btn-outline-primary btn-sm btn-auto" id="mobile_select_all">Pilih Semua</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm btn-auto" id="mobile_deselect_all">Hapus Pilihan</button>
                            
                            <?php if ($user_role == 'admin' || $user_role == 'member') : ?>
                                <input type="submit" class="btn btn-outline-danger btn-sm btn-auto" name="bulk_delete_submit_all" value="Delete All" onclick="return confirm('Delete ALL guests?');"/>
                                <input type="submit" class="btn btn-outline-danger btn-sm btn-auto" name="bulk_delete_submit" value="Delete Selected" onclick="return confirm('Delete selected?');"/>
                            <?php endif;?>
                            
                            <?php if($notifwa == true) { ?>
                                <button type="button" class="btn btn-primary btn-sm starsender_button btn-auto" data-action="bulk">WA Blast</button>
                            <?php } ?>
                        </div>
                    </div>
                </form>
            </div>
            
        </div>
    </div>

    <!-- Edit Modals (Moved outside loop for z-index/stacking context fix) -->
    <?php foreach ($comment_id as $row) : ?>
    <div class="modal fade" id="update_modal<?php echo $row['no_id']?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-pencil-square"></i> Edit Guest</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-start">
                    <form action="" method="post">
                        <div class="mb-3">
                            <label class="form-label">Nama Tamu</label>
                            <input type="hidden" name="no_id" value="<?php echo $row['no_id']?>"/>
                            <input type="text" class="form-control" name="nama" value="<?php echo $row['nama']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Tanggal</label>
                            <input type='text' class="form-control datepicker" name="tgl" value="<?php echo $row['tgl']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Jam Kehadiran</label>
                            <input type="text" class="form-control timepicker" name="jam" value="<?php echo $row['jam']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">No. Whatsapp</label>
                            <input type="text" class="form-control" name="whatsapp" value="<?php echo $row['whatsapp']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Jumlah Tamu</label>
                            <input type="number" class="form-control" name="jumlah_tamu" value="<?php echo isset($row['jumlah_tamu']) ? $row['jumlah_tamu'] : 1; ?>" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Kategori</label>
                            <select name="tamu" class="form-control">
                                <option value="<?php echo $row['tamu']; ?>" selected><?php echo $row['tamu']; ?> (Current)</option>
                                <?php 
                                $res_cat = mysqli_query($koneksi, "SELECT * FROM categories WHERE event_id = '$active_event_id'");
                                while($d_cat = mysqli_fetch_array($res_cat)) {
                                    echo '<option value="'.$d_cat['category_name'].'">'.$d_cat['category_name'].'</option>';
                                } ?>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary w-100" name="update">Update Data</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <!-- Modals Section -->
    
    <!-- Modal Scan -->
    <div class="modal fade" id="Scan" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-qr-code-scan"></i> Scan QR Code</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12 text-center">
                             <div id="reader" style="display: none; width: 100%;"></div>
                        </div>
                    </div>      
                </div>
            </div>
        </div>
    </div>

    <!-- Modal QR Result -->
    <div class="modal fade" id="QrResultModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-person-check-fill"></i> Tambahkan Tamu Scan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="qr-result-form">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control fw-bold fs-5 text-primary bg-light" name="decodedText" id="qr_nama" readonly>
                            <label for="qr_nama">Nama Tamu</label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" name="whatsapp" id="qr_wa" autocomplete="off">
                            <label for="qr_wa">No WA <small>(optional)</small></label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="number" class="form-control" name="jumlah_tamu" id="qr_jumlah" value="1" min="1" required>
                            <label for="qr_jumlah">Jumlah Hadir</label>
                        </div>
                        <div class="form-floating mb-3">
                            <select name="tamuqr" id="qr_kategori" class="form-control">
                                <option value="">-- Pilih Kategori --</option>
                                <?php 
                                $res_cat2 = mysqli_query($koneksi, "SELECT * FROM categories");
                                while($d_cat2 = mysqli_fetch_array($res_cat2)) {
                                    echo '<option value="'.$d_cat2['category_name'].'">'.$d_cat2['category_name'].'</option>';
                                } ?>
                            </select>
                            <label for="qr_kategori">Kategori Tamu</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 py-3" id="btn-save-qr">Tambah Tamu</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Import -->
    <div class="modal fade" id="Import" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-upload"></i> Import CSV</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <form action="import.php" method="post" enctype="multipart/form-data" class="p-3 border rounded border-dashed">
                        <div class="mb-3">
                             <i class="bi bi-file-earmark-spreadsheet display-4 text-muted"></i>
                        </div>
                        <input type="file" class="form-control mb-3" name="file" required>
                        <button type="submit" class="btn btn-primary w-100" name="submit_import">Upload & Import</button>
                        <div class="mt-3">
                            <a href="sample-csv-tamu.csv" class="text-decoration-none"><i class="bi bi-download"></i> Download Sample CSV</a>
                        </div>
                        
                        <div id="contact-picker-container" class="mt-4 pt-3 border-top" style="display: none;">
                            <p class="small text-muted mb-2">Atau import langsung dari kontak HP Anda:</p>
                            <button type="button" class="btn btn-outline-success w-100" id="btn-import-contacts">
                                <i class="bi bi-person-lines-fill"></i> Import dari Kontak HP
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal AddData -->
    <div class="modal fade" id="AddData" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-person-plus"></i> Tambahkan Tamu Manual</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="" method="post" class="p-2">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" name="nama" id="nama_add" placeholder="Nama Tamu" required autocomplete="off">
                            <label for="nama_add">Nama Tamu</label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" name="whatsapp" id="wa_add" placeholder="No WA" autocomplete="off">
                            <label for="wa_add">No WA <small>(optional)</small></label>
                        </div>
                        <div class="form-floating mb-3">
                            <input type="number" class="form-control" name="jumlah_tamu" id="jumlah_add" placeholder="Jumlah Hadir" value="1" min="1" required autocomplete="off">
                            <label for="jumlah_add">Jumlah Hadir</label>
                        </div>
                        <div class="form-floating mb-3">
                            <select name="tamu" id="tamu_add" class="form-control">
                                <option value="">-- Pilih Kategori --</option>
                                <?php 
                                $res_cat3 = mysqli_query($koneksi, "SELECT * FROM categories");
                                while($d_cat3 = mysqli_fetch_array($res_cat3)) {
                                    echo '<option value="'.$d_cat3['category_name'].'">'.$d_cat3['category_name'].'</option>';
                                } ?>
                            </select>
                            <label for="tamu_add">Kategori Tamu</label>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 py-3" name="simpan">Tambah Tamu</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

<?php 
if (isset($_POST['update'])) {
    if (update($_POST) > 0) {
        echo '<script>swal("Success!", "Data updated successfully!", "success").then(() => { window.location="dashboard"; });</script>';
    } else {
        echo '<script>swal("Error!", "Failed to update data.", "error");</script>';
    }
}
?>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="./dist/html5-qrcode.min.js"></script>

<script>
    // QR Code Scanner Logic
    var html5QrcodeScanner;
    var scanning = false;
    
    $(document).ready(function() {
        $('#Scan').on('shown.bs.modal', function () {
            scanning = true; 
            document.getElementById('reader').style.display = 'block';
            startScanning(); 
        });
        
        $('#Scan').on('hidden.bs.modal', function () {
            if (html5QrcodeScanner && scanning) {
                html5QrcodeScanner.clear().catch(error => {
                    console.error("Failed to clear html5QrcodeScanner. ", error);
                });
                scanning = false;
            }
        });
        
        $('#qr-result-form').submit(function(e) {
            e.preventDefault();
            var decodedText = $('#qr_nama').val();
            var tamuqr = $('#qr_kategori').val();
            var jumlah_tamu = $('#qr_jumlah').val();
            var whatsapp = $('#qr_wa').val();
            var btn = $('#btn-save-qr');
            
            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Menyimpan...');
            
            $.ajax({
                url: "submitqr.php",
                method: "POST",
                data: {
                    decodedText: decodedText, 
                    tamuqr: tamuqr,
                    jumlah_tamu: jumlah_tamu,
                    whatsapp: whatsapp
                },
                success: function (response) {
                    window.location.href = '/dashboard';
                },
                error: function() {
                    alert('Gagal menyimpan tamu.');
                    btn.prop('disabled', false).html('Tambah Tamu');
                }
            });
        });
    });

    function startScanning() {
        html5QrcodeScanner = new Html5QrcodeScanner("reader", { fps: 10, qrbox: {width: 250, height: 250} });
        html5QrcodeScanner.render(submitBarcodeData);
    }

    function submitBarcodeData(decodedText) {
        if (scanning) {
            scanning = false;
            
            // Tampilkan popup input hasil scan
            $('#Scan').modal('hide');
            $('#qr_nama').val(decodedText);
            
            setTimeout(() => {
                 $('#QrResultModal').modal('show');
            }, 500);
            
            // Hentikan scanner aktif
            if (html5QrcodeScanner) {
                html5QrcodeScanner.clear().catch(error => {
                    console.error("Failed to clear html5QrcodeScanner. ", error);
                });
            }
        }
    }

    // Date/Time Pickers
    $(document).ready(function () {
        $(".datepicker").datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            todayHighlight: true,
        });
        $('.timepicker').datetimepicker({
            format: 'HH:mm'
        });
        
        // DataTable
        $('#data').dataTable({
            "lengthChange": true, 
            "paging": true,
            "language": {
                "search": "",
                "searchPlaceholder": "Search guests..."
            },
            "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                   "<'row'<'col-sm-12'tr>>" +
                   "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        });
    });

    // Select All Checkbox
    $(document).ready(function(){
        $('#select_all').on('click',function(){
            var table = $('#data').DataTable();
            var checked = this.checked;
            table.rows().every(function() {
                $(this.node()).find('.checkbox').prop('checked', checked);
            });
        });
        
        $('#mobile_select_all').on('click', function() {
            $('.checkbox').prop('checked', true);
            // Also update all rows in DataTable (in case of pagination)
            if ($.fn.DataTable.isDataTable('#data')) {
                var table = $('#data').DataTable();
                table.rows().nodes().to$().find('.checkbox').prop('checked', true);
            }
            $('#select_all').prop('checked', true);
        });
        
        $('#mobile_deselect_all').on('click', function() {
            $('.checkbox').prop('checked', false);
            // Also update all rows in DataTable
            if ($.fn.DataTable.isDataTable('#data')) {
                var table = $('#data').DataTable();
                table.rows().nodes().to$().find('.checkbox').prop('checked', false);
            }
            $('#select_all').prop('checked', false);
        });
        
        // Toggle checkbox when clicking the row/card (mobile only)
        $(document).on('click', '.guest-row', function(e) {
            if ($(window).width() <= 768) {
                // Don't toggle if clicking buttons, links, or inputs
                if (!$(e.target).closest('input, button, a, i, .mobile-collapse-row, .single_select').length) {
                    var chk = $(this).find('.checkbox');
                    chk.prop('checked', !chk.prop('checked')).trigger('change');
                }
            }
        });
        
        $('.checkbox').on('click',function(){
            if($('.checkbox:checked').length == $('.checkbox').length){
                $('#select_all').prop('checked',true);
            }else{
                $('#select_all').prop('checked',false);
            }
        });
    });

    // WA Sending Logic (StarSender & OneSender)
    // Combined Logic for cleaner code
    function sendBlast(button, type) {
        $(button).attr('disabled', 'disabled');
        var id = $(button).attr("id");
        var action = $(button).data("action");
        var bulk_data = [];
        
        if(action == 'single') {
            bulk_data.push({ wa: $(button).data("wa"), pesan: $(button).data("pesan") });
        } else {
            // Use DataTable API to find checked boxes across all pages
            var table = $('#data').DataTable();
            table.rows().every(function() {
                var chk = $(this.node()).find('.single_select:checked');
                if (chk.length > 0) {
                    bulk_data.push({ 
                        wa: chk.attr("data-wa") || chk.data("wa"), 
                        pesan: chk.attr("data-pesan") || chk.data("pesan") 
                    });
                }
            });
        }
        
        if(action != 'single' && bulk_data.length === 0) {
            swal("Info", "Pilih setidaknya satu tamu", "info");
            $(button).removeAttr('disabled');
            return;
        }
        
        // Define data object key based on type
        var ajaxData = {};
        if (type === 'starsender') {
            ajaxData = { bulk_send_submit_starsender: bulk_data };
        } else {
            ajaxData = { bulk_send_submit_onesender: bulk_data };
        }

        $.ajax({
            url: "reset.php",
            method: "POST",
            data: ajaxData,
            dataType: "json",
            beforeSend: function(){
                if(action === 'single') {
                    $(button).html('<span class="spinner-border spinner-border-sm"></span>');
                } else {
                     // For bulk button
                     $(button).html('Sending...');
                }
            },
            success: function(response){
                if(response == 'success') {
                    if(action == 'single') $(button).text('Sent').removeClass('btn-primary').addClass('btn-success');
                    else swal("Success", "Blast sent successfully", "success");
                } else {
                    if(action == 'single') $(button).text('Failed').removeClass('btn-primary').addClass('btn-danger');
                    else swal("Error", "Failed to send blast", "error");
                }
                $(button).removeAttr('disabled');
            }
        });
    }

    $(document).ready(function(){
        $('.starsender_button').click(function(){ sendBlast(this, 'starsender'); });
        $('.email_button').click(function(){ sendBlast(this, 'onesender'); });
    });

    document.addEventListener('DOMContentLoaded', () => {
        const contactPickerContainer = document.getElementById('contact-picker-container');
        const btnImportContacts = document.getElementById('btn-import-contacts');
        
        const supported = ('contacts' in navigator && 'ContactsManager' in window);
        
        if (supported && contactPickerContainer) {
            contactPickerContainer.style.display = 'block';
            
            btnImportContacts.addEventListener('click', async () => {
                const props = ['name', 'tel'];
                const opts = {multiple: true};
                
                try {
                    btnImportContacts.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Loading...';
                    btnImportContacts.disabled = true;
                    
                    const contacts = await navigator.contacts.select(props, opts);
                    if (!contacts.length) {
                        btnImportContacts.innerHTML = '<i class="bi bi-person-lines-fill"></i> Import dari Kontak HP';
                        btnImportContacts.disabled = false;
                        return;
                    }
                    
                    const formattedContacts = contacts.map(c => ({
                        name: c.name ? c.name[0] : '',
                        tel: c.tel ? c.tel[0] : ''
                    })).filter(c => c.name || c.tel);
                    
                    const response = await fetch('submitcontacts.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ contacts: formattedContacts })
                    });
                    
                    const result = await response.json();
                    if (result.status === 'success') {
                        swal("Success", `${result.added} kontak berhasil diimport!`, "success").then(() => {
                            window.location.reload();
                        });
                    } else {
                        swal("Error", "Gagal mengimport kontak.", "error");
                        btnImportContacts.innerHTML = '<i class="bi bi-person-lines-fill"></i> Import dari Kontak HP';
                        btnImportContacts.disabled = false;
                    }
                } catch (ex) {
                    console.info("Contact picker error user canceled or failure", ex);
                    btnImportContacts.innerHTML = '<i class="bi bi-person-lines-fill"></i> Import dari Kontak HP';
                    btnImportContacts.disabled = false;
                }
            });
        }
    });
</script>

</body>
</html>