<?php
include_once "../global.php";

$pageTitle = "WhatsApp Bulk Send - ";
include_once '../header.php';

$contacts = $dbF->getRows("SELECT phone_e164, COALESCE(NULLIF(display_name,''), phone_e164) AS display_name 
FROM whatsapp_contacts ORDER BY display_name ASC LIMIT 2000");
?>

<!--breadcrumb-->
<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
    <div class="breadcrumb-title pe-3">WhatsApp Management</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item"><a href="javascript:;"></a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">WhatsApp Bulk Send</li>
            </ol>
        </nav>
    </div>
</div>
<!--end breadcrumb-->
<div class="card">
    <div class="card-body p-4">
        <h5 class="mb-4">WhatsApp Bulk Send</h5>
        <form id="waBulkForm" class="row g-3" method="post">
            <div class="col-md-8">
                <label class="form-label">Recipients</label>
                <select id="recipients" name="recipients[]" class="multiple-select-field"
                    data-placeholder="Select Recipients" multiple required>
                    <?php
                    foreach ($contacts as $c) {
                        $name = trim($c['display_name']);
                        $phone = $c['phone_e164'];
                        $label = ($name === $phone) ? $phone : "{$name} ({$phone})";
                    ?>
                        <option value="<?php echo $phone; ?>"><?php echo $label; ?></option>
                    <?php } ?>
                </select>
                <div class="form-text mt-1">
                    Tip: use both selectors and CSV together - duplicates are auto-ignored.
                </div>
            </div>
            <div class="col-md-4">
                <label class="form-label">Upload CSV (optional)</label>
                <input type="file" name="csvfile" id="csvfile" class="form-control" accept=".csv,text/csv">
                <div class="form-text">
                    Columns accepted (any order): <code>phone</code>/<code>number</code>/<code>msisdn</code>/<code>whatsapp</code>,
                    and optional <code>name</code>. If no headers: first column = phone, second = name.
                </div>
            </div>
            <div class="col-md-4">
                <label class="form-label">Schedule At (optional, Y-m-d H:i:s)</label>
                <input type="text" name="schedule_at" id="schedule_at" class="form-control date-time"
                    placeholder="2025-11-11 14:30:00">
            </div>
            <div class="col-md-8">
                <label class="form-label">Media URL (optional)</label>
                <input type="url" name="media" id="media" class="form-control" placeholder="https://icrm.com.pk/webImages/image.jpg">
            </div>
            <div class="col-md-12">
                <label class="form-label">Message</label>
                <textarea name="body" id="body" class="form-control" rows="4" placeholder="Your message"></textarea>
            </div>
            <div class="col-md-12">
                <button type="submit" class="btn btn-grd-primary px-4">Enqueue</button>
            </div>
        </form>
        <pre id="bulkResult" class="mt-3 small"></pre>
    </div>
</div>
<script>
    $("#waBulkForm").on("submit", function(e) {
        e.preventDefault();
        $.ajax({
            url: '<?php echo WEB_URL; ?>/ajax_call?page=waBulkEnqueue',
            type: 'POST',
            data: new FormData(this),
            processData: false,
            contentType: false,
            dataType: 'json',
            beforeSend: function() {
                $("#spinner-overlay").fadeIn('slow');
            },
            success: function(res) {
                $("#bulkResult").text(JSON.stringify(res, null, 2));
                if (res.status === 'success') {
                    showAlert(`Enqueued: ${res.enqueued}. Skipped: ${res.skipped.length}.`);
                } else {
                    showAlert(res.message || 'Error');
                }
            },
            error: function(xhr) {
                $("#bulkResult").text(xhr.responseText || 'Error');
            },
            complete: function() {
                $("#spinner-overlay").fadeOut('slow');
            }
        });
    });
</script>
<?php include_once '../footer.php'; ?>