<?php
session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

requireLogin();
requireRole(['admin', 'manager']);

$accessibleBranches = getAccessibleBranches($pdo);
if (empty($accessibleBranches)) {
    die('No branch access assigned.');
}

$branchPlaceholders = implode(',', array_fill(0, count($accessibleBranches), '?'));
$billNumber = strtoupper(trim((string)($_GET['bill'] ?? '')));
$promoAllMessage = '';
$promoJobMessage = '';
$testPhone = '';
$testMessage = '';
$selectedJobTypes = [];
$messageState = null;
$resultResponse = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf($_POST['csrf_token'] ?? null);

    $mode = trim((string)($_POST['mode'] ?? ''));

    if ($mode === 'invoice') {
        $billNumber = strtoupper(trim((string)($_POST['bill_number'] ?? '')));
        $messageState = sendInvoiceLinkSMS($pdo, $billNumber, $accessibleBranches);
    } elseif ($mode === 'promo_all') {
        $promoAllMessage = trim((string)($_POST['message'] ?? ''));
        if ($promoAllMessage === '') {
            $messageState = ['status' => 'error', 'message' => 'Enter a promotional SMS before sending.'];
        } elseif (mb_strlen($promoAllMessage) > 160) {
            $messageState = ['status' => 'error', 'message' => 'Promotional SMS must stay within 160 characters.'];
        } else {
            $messageState = sendBulkCustomerSMS($pdo, $promoAllMessage, $accessibleBranches);
            $resultResponse = $messageState['response'] ?? null;
        }
    } elseif ($mode === 'promo_job_types') {
        $promoJobMessage = trim((string)($_POST['message'] ?? ''));
        $selectedJobTypes = array_values(array_unique(array_filter(array_map('intval', $_POST['job_types'] ?? []))));
        if ($promoJobMessage === '') {
            $messageState = ['status' => 'error', 'message' => 'Enter a promotional SMS before sending.'];
        } elseif (mb_strlen($promoJobMessage) > 160) {
            $messageState = ['status' => 'error', 'message' => 'Promotional SMS must stay within 160 characters.'];
        } else {
            $messageState = sendJobTypeCustomerSMS($pdo, $promoJobMessage, $accessibleBranches, $selectedJobTypes);
            $resultResponse = $messageState['response'] ?? null;
        }
    } elseif ($mode === 'test') {
        $testPhone = trim((string)($_POST['phone'] ?? ''));
        $testMessage = trim((string)($_POST['message'] ?? ''));

        if ($testPhone === '' || $testMessage === '') {
            $messageState = ['status' => 'error', 'message' => 'Enter both a test phone number and message.'];
        } elseif (mb_strlen($testMessage) > 160) {
            $messageState = ['status' => 'error', 'message' => 'Test SMS must stay within 160 characters for campaign validation.'];
        } else {
            $messageState = sendSmsMessage($testPhone, $testMessage);
            $resultResponse = $messageState['response'] ?? null;
        }
    } else {
        $messageState = ['status' => 'error', 'message' => 'Unknown SMS action requested.'];
    }
}

$customerCountStmt = $pdo->prepare("
    SELECT COUNT(DISTINCT b.customer_id)
    FROM bills b
    JOIN customers c ON c.customer_id = b.customer_id
    WHERE b.branch_id IN ($branchPlaceholders)
      AND c.contact_number IS NOT NULL
      AND c.contact_number <> ''
");
$customerCountStmt->execute($accessibleBranches);
$reachableCustomers = (int)$customerCountStmt->fetchColumn();

$jobTypeStmt = $pdo->prepare("
    SELECT
        jt.job_type_id,
        jt.job_name,
        COUNT(DISTINCT b.customer_id) AS customer_count,
        COALESCE(SUM(j.qty), 0) AS total_qty
    FROM jobs j
    JOIN bills b ON b.bill_id = j.bill_id
    JOIN customers c ON c.customer_id = b.customer_id
    JOIN job_types jt ON jt.job_type_id = j.job_type_id
    WHERE b.branch_id IN ($branchPlaceholders)
      AND c.contact_number IS NOT NULL
      AND c.contact_number <> ''
    GROUP BY jt.job_type_id, jt.job_name
    ORDER BY customer_count DESC, total_qty DESC, jt.job_name ASC
");
$jobTypeStmt->execute($accessibleBranches);
$jobTypeOptions = $jobTypeStmt->fetchAll(PDO::FETCH_ASSOC);

$jobTypeCount = count($jobTypeOptions);
$providerName = 'SMSlenz';

include __DIR__ . '/../includes/header.php';
?>

<section class="summary-strip mb-4">
    <div class="summary-card">
        <div class="label">Reachable Customers</div>
        <div class="value"><?= $reachableCustomers ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Job Type Audiences</div>
        <div class="value"><?= $jobTypeCount ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Campaign Limit</div>
        <div class="value">160 chars</div>
    </div>
    <div class="summary-card">
        <div class="label">Provider</div>
        <div class="value"><?= htmlspecialchars($providerName) ?></div>
    </div>
</section>

<div class="section-stack">
    <section class="app-card p-4">
        <div class="page-toolbar">
            <div>
                <span class="app-eyebrow">Admin Campaigns</span>
                <h2 class="mb-1">SMS Campaign</h2>
                <p class="text-muted mb-0">Run 160-character promotional SMS campaigns, target specific job audiences, and verify provider delivery from the live support route.</p>
            </div>
        </div>

        <?php if ($messageState): ?>
            <div class="alert <?= $messageState['status'] === 'success' ? 'alert-success' : 'alert-danger' ?> border-0 rounded-4">
                <?= htmlspecialchars((string)$messageState['message']) ?>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-xl-6">
                <div class="app-card p-4 h-100">
                    <div class="app-eyebrow mb-2">Promo Blast</div>
                    <h3 class="h4 mb-2">All reachable customers</h3>
                    <p class="text-muted">Send one promotional message to every customer phone number found inside your accessible branches.</p>

                    <form method="POST" class="stack-form mt-4">
                        <?= csrfField() ?>
                        <input type="hidden" name="mode" value="promo_all">
                        <div>
                            <label class="form-label fw-semibold" for="promo_all_message">Promotional message</label>
                            <textarea class="form-control campaign-message" id="promo_all_message" name="message" rows="5" maxlength="160" placeholder="Example: WashHouse pickup slots are open this week. Reply or call 0770233310 to book your laundry pickup." required><?= htmlspecialchars($promoAllMessage) ?></textarea>
                            <div class="muted-note mt-2"><span data-counter-for="promo_all_message"><?= mb_strlen($promoAllMessage) ?></span>/160 characters</div>
                        </div>
                        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                            <div class="muted-note">Distinct customer numbers only. Branch-scoped automatically.</div>
                            <button type="submit" class="btn btn-retro">Send All-Customer Promo</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-xl-6">
                <div class="app-card p-4 h-100">
                    <div class="app-eyebrow mb-2">Segmented Promo</div>
                    <h3 class="h4 mb-2">Customers by ordered job types</h3>
                    <p class="text-muted">Select one or more job types to target customers who have actually ordered those services.</p>

                    <form method="POST" class="stack-form mt-4">
                        <?= csrfField() ?>
                        <input type="hidden" name="mode" value="promo_job_types">
                        <div>
                            <label class="form-label fw-semibold" for="job_types">Job type audience</label>
                            <select class="form-select" id="job_types" name="job_types[]" multiple size="10" required>
                                <?php foreach ($jobTypeOptions as $jobType): ?>
                                    <option value="<?= (int)$jobType['job_type_id'] ?>" <?= in_array((int)$jobType['job_type_id'], $selectedJobTypes, true) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($jobType['job_name']) ?> | <?= (int)$jobType['customer_count'] ?> customers | <?= number_format((float)$jobType['total_qty'], 1) ?> qty
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="muted-note mt-2">Use Ctrl/Cmd click to select multiple job types.</div>
                        </div>
                        <div>
                            <label class="form-label fw-semibold" for="promo_job_message">Promotional message</label>
                            <textarea class="form-control campaign-message" id="promo_job_message" name="message" rows="5" maxlength="160" placeholder="Example: Special care offer this week for dry cleaning and shirt pressing. Call WashHouse on 0770233310 for pickup." required><?= htmlspecialchars($promoJobMessage) ?></textarea>
                            <div class="muted-note mt-2"><span data-counter-for="promo_job_message"><?= mb_strlen($promoJobMessage) ?></span>/160 characters</div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-retro">Send Targeted Promo</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="app-card p-4 h-100">
                    <div class="app-eyebrow mb-2">Provider Check</div>
                    <h3 class="h4 mb-2">Test SMS functionality</h3>
                    <p class="text-muted">Send a short test message to a phone number before launching a campaign.</p>

                    <form method="POST" class="stack-form mt-4">
                        <?= csrfField() ?>
                        <input type="hidden" name="mode" value="test">
                        <div class="form-grid">
                            <div>
                                <label class="form-label fw-semibold" for="test_phone">Phone Number</label>
                                <input class="form-control" type="text" id="test_phone" name="phone" value="<?= htmlspecialchars($testPhone) ?>" placeholder="0770233310" required>
                            </div>
                        </div>
                        <div>
                            <label class="form-label fw-semibold" for="test_message">Test message</label>
                            <textarea class="form-control campaign-message" id="test_message" name="message" rows="4" maxlength="160" placeholder="WashHouse SMS test. If you receive this, provider delivery is working." required><?= htmlspecialchars($testMessage) ?></textarea>
                            <div class="muted-note mt-2"><span data-counter-for="test_message"><?= mb_strlen($testMessage) ?></span>/160 characters</div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-retro">Send Test SMS</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="app-card p-4 h-100">
                    <div class="app-eyebrow mb-2">Support Tool</div>
                    <h3 class="h4 mb-2">Send invoice link SMS</h3>
                    <p class="text-muted">Keep the one-to-one support action here for invoice resends during customer calls.</p>

                    <form method="POST" class="stack-form mt-4">
                        <?= csrfField() ?>
                        <input type="hidden" name="mode" value="invoice">
                        <div>
                            <label class="form-label fw-semibold" for="bill_number">Bill Number</label>
                            <input class="form-control" type="text" id="bill_number" name="bill_number" value="<?= htmlspecialchars($billNumber) ?>" placeholder="1-15655" required>
                        </div>
                        <div class="table-actions">
                            <button type="submit" class="btn btn-retro">Send Invoice SMS</button>
                            <?php if ($billNumber !== ''): ?>
                                <a href="/pages/invoice.php?bill=<?= urlencode($billNumber) ?>" class="btn btn-outline-secondary rounded-pill px-4">Open Invoice</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <?php if ($resultResponse && $messageState): ?>
            <details class="mt-4">
                <summary class="fw-semibold">Provider response</summary>
                <pre class="mt-3 p-3 rounded-4 bg-light border small mb-0"><?= htmlspecialchars((string)$resultResponse) ?></pre>
            </details>
        <?php endif; ?>
    </section>
</div>

<script>
document.querySelectorAll('.campaign-message').forEach((field) => {
    const counter = document.querySelector(`[data-counter-for="${field.id}"]`);
    if (!counter) {
        return;
    }

    const updateCounter = () => {
        counter.textContent = field.value.length.toString();
    };

    field.addEventListener('input', updateCounter);
    updateCounter();
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
