<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$adminPageTitle = 'Phone Numbers';
$db = getDB();
$errors  = [];
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update') {
        // Update all 5 numbers at once
        $ids     = $_POST['id']     ?? [];
        $phones  = $_POST['phone']  ?? [];
        $wa      = $_POST['whatsapp'] ?? [];
        $labels  = $_POST['label']  ?? [];
        $active  = $_POST['active'] ?? [];

        $stmt = $db->prepare("UPDATE contact_numbers SET phone_number=?, whatsapp_number=?, label=?, is_active=? WHERE id=?");
        foreach ($ids as $i => $nid) {
            $phoneVal = trim($phones[$i] ?? '');
            if (!$phoneVal) { $errors[] = "Phone number for row " . ($i+1) . " cannot be empty."; continue; }
            $stmt->execute([
                $phoneVal,
                trim($wa[$i] ?? ''),
                trim($labels[$i] ?? ''),
                isset($active[$i]) ? 1 : 0,
                (int)$nid
            ]);
        }
        if (empty($errors)) $success = 'Phone numbers updated successfully!';

    } elseif ($action === 'add') {
        $total = (int)$db->query("SELECT COUNT(*) FROM contact_numbers")->fetchColumn();
        if ($total >= 5) {
            $errors[] = 'Maximum 5 phone numbers allowed. Delete one first.';
        } else {
            $phone = trim($_POST['new_phone'] ?? '');
            $wa    = trim($_POST['new_whatsapp'] ?? '');
            $label = trim($_POST['new_label'] ?? '');
            if (!$phone) $errors[] = 'Phone number is required.';
            else {
                $db->prepare("INSERT INTO contact_numbers (phone_number, whatsapp_number, label, is_active) VALUES (?,?,?,1)")
                   ->execute([$phone, $wa, $label]);
                $success = 'Phone number added!';
            }
        }

    } elseif ($action === 'delete') {
        $delId = (int)($_POST['del_id'] ?? 0);
        if ($delId) {
            $db->prepare("DELETE FROM contact_numbers WHERE id=?")->execute([$delId]);
            $success = 'Phone number deleted.';
        }
    }
}

$numbers = getAllPhones();
include __DIR__ . '/partials/admin_header.php';
?>

<?php if ($success): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle me-2"></i><?= sanitize($success) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if ($errors): ?>
<div class="alert alert-danger">
    <?php foreach ($errors as $e): ?><div><i class="fas fa-times-circle me-2"></i><?= sanitize($e) ?></div><?php endforeach; ?>
</div>
<?php endif; ?>

<div class="row g-4">
<!-- Existing Numbers -->
<div class="col-12">
<div class="table-card">
    <div class="card-header"><i class="fas fa-phone me-2 text-primary"></i>Contact Numbers (<?= count($numbers) ?>/5)</div>
    <div class="p-4">
        <p class="text-muted small mb-3">
            <i class="fas fa-info-circle me-1 text-info"></i>
            The <strong>"Call Now"</strong> button on product pages randomly selects one of the active numbers below.
            The <strong>WhatsApp</strong> button uses the first active WhatsApp number.
        </p>
        <?php if (empty($numbers)): ?>
            <p class="text-muted text-center py-3">No numbers added yet.</p>
        <?php else: ?>
        <form method="POST" action="">
            <input type="hidden" name="action" value="update">
            <div class="table-responsive">
                <table class="table align-middle mb-3">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Label</th>
                            <th>Phone Number (for calls)</th>
                            <th>WhatsApp Number (digits only)</th>
                            <th>Active</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($numbers as $i => $num): ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td>
                            <input type="hidden" name="id[]" value="<?= $num['id'] ?>">
                            <input type="text" name="label[]" class="form-control form-control-sm" value="<?= sanitize($num['label'] ?? '') ?>" placeholder="e.g. Sales 1">
                        </td>
                        <td>
                            <input type="text" name="phone[]" class="form-control form-control-sm" value="<?= sanitize($num['phone_number']) ?>" placeholder="+919876543210" required>
                        </td>
                        <td>
                            <input type="text" name="whatsapp[]" class="form-control form-control-sm" value="<?= sanitize($num['whatsapp_number'] ?? '') ?>" placeholder="919876543210">
                            <small class="text-muted">No + or spaces</small>
                        </td>
                        <td class="text-center">
                            <input type="checkbox" name="active[<?= $i ?>]" class="form-check-input" <?= $num['is_active'] ? 'checked' : '' ?>>
                        </td>
                        <td>
                            <button type="button" class="btn btn-sm btn-outline-danger"
                                    onclick="deleteNumber(<?= $num['id'] ?>, '<?= addslashes(sanitize($num['phone_number'])) ?>')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save me-2"></i>Save All Changes
            </button>
        </form>
        <?php endif; ?>
    </div>
</div>
</div>

<!-- Add New Number -->
<?php if (count($numbers) < 5): ?>
<div class="col-md-6">
<div class="table-card">
    <div class="card-header"><i class="fas fa-plus-circle me-2 text-success"></i>Add Phone Number</div>
    <div class="p-4">
        <form method="POST" action="">
            <input type="hidden" name="action" value="add">
            <div class="mb-3">
                <label class="form-label fw-semibold">Label</label>
                <input type="text" name="new_label" class="form-control" placeholder="e.g. Sales, Support">
            </div>
            <div class="mb-3">
                <label class="form-label fw-semibold">Phone Number *</label>
                <input type="text" name="new_phone" class="form-control" placeholder="+919876543210" required>
            </div>
            <div class="mb-3">
                <label class="form-label fw-semibold">WhatsApp Number</label>
                <input type="text" name="new_whatsapp" class="form-control" placeholder="919876543210 (no + or spaces)">
            </div>
            <button type="submit" class="btn btn-success">
                <i class="fas fa-plus me-2"></i>Add Number
            </button>
        </form>
    </div>
</div>
</div>
<?php endif; ?>
</div>

<!-- Hidden delete form -->
<form id="deleteForm" method="POST" action="" style="display:none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="del_id" id="delId">
</form>

<?php
$extraJS = <<<JS
<script>
function deleteNumber(id, phone) {
    if (confirm('Delete number: ' + phone + '?')) {
        document.getElementById('delId').value = id;
        document.getElementById('deleteForm').submit();
    }
}
</script>
JS;
include __DIR__ . '/partials/admin_footer.php';
?>
