<?php
// ---- MUST BE THE VERY FIRST LINE ---- //
session_start();

// Include DB and Header (after session_start)
include "../include/db.php";
include "include/header.php";

// Your API Token
$api_token = "91711424041761639844ac5e020e9badd3d1d8efbcbd5ba4ed7b";
$api_url = "https://api.bdbulksms.net/api.php?json";

// Count total valid users
$total_stmt = $conn->query("SELECT COUNT(*) as total FROM users WHERE phone != '' AND phone IS NOT NULL");
$total_row = $total_stmt->fetch_assoc();
$total_users = $total_row['total'];

// Handle Bulk SMS Send
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_bulk_sms'])) {
    $message = trim($_POST['message'] ?? '');

    // Validation
    if (empty($message)) {
        $errors[] = 'Message is required';
    }
    if (strlen($message) > 160) {
        $errors[] = 'Message cannot exceed 160 characters';
    }

    if (empty($errors)) {
        // Fetch all valid phone numbers
        $stmt = $conn->prepare("SELECT name, phone FROM users WHERE phone != '' AND phone IS NOT NULL");
        $stmt->execute();
        $result = $stmt->get_result();
        $users = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (empty($users)) {
            $errors[] = 'No valid phone numbers found in database';
        } else {
            $valid_numbers = [];
            foreach ($users as $user) {
                $phone = preg_replace('/[^0-9+]/', '', $user['phone']);
                if (strlen($phone) >= 10 && strlen($phone) <= 15) {
                    $valid_numbers[] = $phone;
                }
            }

            if (empty($valid_numbers)) {
                $errors[] = 'No valid phone numbers to send SMS';
            } else {
                $to_numbers = implode(',', $valid_numbers);

                $data = [
                    'to'      => $to_numbers,
                    'message' => $message,
                    'token'   => $api_token
                ];

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_url);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_ENCODING, '');
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);

                $response = curl_exec($ch);
                $curl_error = curl_error($ch);
                curl_close($ch);

                if ($curl_error) {
                    $errors[] = 'cURL Error: ' . $curl_error;
                } else {
                    $result = json_decode($response, true);

                    if (json_last_error() === JSON_ERROR_NONE && is_array($result)) {
                        $sent_count = 0;
                        $details = [];

                        foreach ($result as $item) {
                            if (isset($item['status']) && strtoupper($item['status']) === 'SENT') {
                                $sent_count++;
                                $details[] = "<strong>{$item['to']}</strong>: {$item['statusmsg']}";
                            } else {
                                $details[] = "<strong>{$item['to']}</strong>: <span class='text-danger'>{$item['statusmsg']}</span>";
                            }
                        }

                        if ($sent_count > 0) {
                            $success = "Bulk SMS sent successfully!<br>Total Sent: $sent_count out of " . count($valid_numbers);
                            $sms_result = "<div class='mt-3 p-3 bg-light rounded border'><small>" . implode('<br>', $details) . "</small></div>";
                        } else {
                            $errors[] = "No SMS was sent. Check API response.";
                        }
                    } else {
                        // Fallback: old pipe format
                        $parts = explode('|', trim($response));
                        if (count($parts) >= 4 && strtolower($parts[0]) === 'success') {
                            $total = $parts[1];
                            $cost = $parts[2];
                            $balance = $parts[3];
                            $success = "Bulk SMS sent!<br>Total: $total | Cost: ৳$cost | Balance: ৳$balance";
                            $sms_result = "<pre class='bg-light p-3 rounded mt-3 text-success'>$response</pre>";
                        } else {
                            $errors[] = "API Error: $response";
                        }
                    }
                }
            }
        }
    }

    // Flash Message
    if ($success) {
        $_SESSION['result'] = $success . $sms_result;
        $_SESSION['status'] = 'ok';
    } elseif (!empty($errors)) {
        $_SESSION['result'] = implode('<br>', $errors);
        $_SESSION['status'] = 'error';
    }
    header("Location: bulk_sms.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk SMS - IT Galaxy Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Roboto:wght@700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            color: #333;
        }
        .content {
            margin-left: 250px;
            padding: 2rem;
            min-height: 100vh;
        }
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(135deg, #1E293B 0%, #334155 100%);
            color: white;
            padding: 1.5rem;
        }
        .card-header h2 {
            font-family: 'Roboto', sans-serif;
            font-weight: 700;
        }
        .form-control, .form-control:focus {
            border-radius: 8px;
            padding: 12px;
            box-shadow: none;
        }
        .btn-primary {
            background: linear-gradient(45deg, #10b981, #34d399);
            border: none;
            padding: 14px 32px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1.1rem;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background: linear-gradient(45deg, #059669, #10b981);
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
        }
        .btn-back {
            background: #6c757d;
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            text-decoration: none;
            display: inline-block;
        }
        .info-box {
            background: #ecfdf5;
            border-left: 5px solid #10b981;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 15px;
        }
        .char-count {
            font-size: 0.875rem;
            color: #6b7280;
            text-align: right;
        }
        .alert {
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            .content { margin-left: 0; padding: 1rem; }
            .card-header { padding: 1rem; }
            .btn-primary { font-size: 1rem; padding: 12px 24px; }
        }
    </style>
</head>
<body>
    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40 backdrop-blur-md bg-white/10">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div>
            <a href="contacts.php" class="btn-back">
                Back to Messages
            </a>
        </div>
    </nav>

    <div class="content">
        <div class="max-w-4xl mx-auto">
            <div class="card">
                <div class="card-header">
                    <h2 class="mb-0">Bulk SMS to All Users</h2>
                    <p class="mb-0 opacity-90">Send SMS to every user in the database</p>
                </div>

                <div class="card-body p-4">
                    <!-- Info Box -->
                    <div class="info-box">
                        <strong>Total Users with Phone:</strong> <?php echo $total_users; ?><br>
                        <small class="text-muted">Only valid phone numbers will receive SMS</small>
                    </div>

                    <!-- Session Message -->
                    <?php if (isset($_SESSION['status'])): ?>
                        <div class="alert alert-<?php echo $_SESSION['status'] == 'ok' ? 'success' : 'danger'; ?>">
                            <?php 
                            echo $_SESSION['result']; 
                            unset($_SESSION['result'], $_SESSION['status']);
                            ?>
                        </div>
                    <?php endif; ?>

                    <!-- Bulk SMS Form -->
                    <form method="POST" onsubmit="return validateBulkSMS();">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Message (Max 160 chars)</label>
                            <textarea name="message" id="sms_message" class="form-control" rows="6" 
                                      placeholder="Type your message..." 
                                      onkeyup="updateCharCount()" required><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
                            <div class="char-count">Characters: <span id="char_count">0</span>/160</div>
                        </div>

                        <div class="d-flex gap-3">
                            <button type="submit" name="send_bulk_sms" class="btn btn-primary">
                                Send to All Users
                            </button>
                            <a href="contacts.php" class="btn btn-back">
                                Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include "include/footer.php"; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateCharCount() {
            const msg = document.getElementById('sms_message').value;
            const count = msg.length;
            document.getElementById('char_count').textContent = count;
            document.getElementById('char_count').style.color = count > 160 ? 'red' : '#6b7280';
        }

        function validateBulkSMS() {
            const msg = document.getElementById('sms_message').value;
            if (msg.length > 160) {
                alert('Message cannot exceed 160 characters!');
                return false;
            }
            return confirm('Send SMS to ALL users? This may take time and cost balance.');
        }

        window.onload = updateCharCount;
    </script>
</body>
</html>