<?php include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/whatsapp_lib.php';

if ($userdata["role"] != 'Admin') {
    echo '<script>window.location.href = "dashboard";</script>';
    exit;
}

$message = null;

// ---- Save gateway connection settings ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_gateway'])) {
    $url = trim($_POST['gateway_url'] ?? '');
    $keyInput = trim($_POST['gateway_api_key'] ?? '');
    $enabled = isset($_POST['notifications_enabled']) ? 1 : 0;

    $existing = mysqli_fetch_assoc(mysqli_query($conn, "SELECT whatsapp_gateway_api_key FROM site_settings LIMIT 1"));
    $key = ($keyInput !== '') ? $keyInput : ($existing['whatsapp_gateway_api_key'] ?? '');

    $stmt = $conn->prepare("UPDATE site_settings SET whatsapp_gateway_url = ?, whatsapp_gateway_api_key = ?, whatsapp_notifications_enabled = ?");
    $stmt->bind_param("ssi", $url, $key, $enabled);
    $stmt->execute();
    $message = ['type' => 'success', 'text' => 'Gateway settings saved.'];
}

// ---- Register a new number + start connecting ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_connect'])) {
    $label = trim($_POST['label'] ?? 'WhatsApp Account');
    $phone = preg_replace('/[^0-9]/', '', $_POST['phone_number'] ?? '');
    $method = ($_POST['method'] ?? 'qr') === 'code' ? 'code' : 'qr';
    $accountId = 'wa_' . substr(md5($phone . time()), 0, 10);

    $stmt = $conn->prepare("INSERT INTO whatsapp_accounts (account_id, label, phone_number, status) VALUES (?, ?, ?, 'connecting')");
    if ($stmt) {
        $stmt->bind_param("sss", $accountId, $label, $phone);
        $stmt->execute();
    }

    $result = wa_start_connect($conn, $accountId, $method, $phone);
    if (!$result['ok']) {
        $message = ['type' => 'error', 'text' => $result['message']];
    } else {
        echo '<script>window.location.href = "whatsapp_gateway?connecting=' . urlencode($accountId) . '&method=' . urlencode($method) . '";</script>';
        exit;
    }
}

// ---- Disconnect a number ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['disconnect_account'])) {
    $accountId = $_POST['account_id'] ?? '';
    wa_disconnect($conn, $accountId);
    $conn->query("DELETE FROM whatsapp_accounts WHERE account_id = '" . mysqli_real_escape_string($conn, $accountId) . "'");
    echo '<script>window.location.href = "whatsapp_gateway";</script>';
    exit;
}

// ---- Manual send ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_send'])) {
    $to = preg_replace('/[^0-9]/', '', $_POST['manual_to'] ?? '');
    $msg = trim($_POST['manual_message'] ?? '');
    $result = send_whatsapp_message($conn, $to, $msg);
    $message = $result['ok']
        ? ['type' => 'success', 'text' => 'Message sent from account: ' . ($result['sent_from'] ?? 'unknown')]
        : ['type' => 'error', 'text' => $result['message'] ?? 'Send failed'];
}

$settings = mysqli_fetch_assoc(mysqli_query($conn, "SELECT whatsapp_gateway_url, whatsapp_gateway_api_key, whatsapp_notifications_enabled FROM site_settings LIMIT 1"));
$gatewayConfigured = wa_gateway_configured($conn);

$accountsRes = $conn->query("SELECT * FROM whatsapp_accounts ORDER BY added_at DESC");
$accountRows = [];
if ($accountsRes) { while ($r = $accountsRes->fetch_assoc()) { $accountRows[] = $r; } }

// Refresh live status for each saved account from the gateway itself.
$liveStatuses = [];
if ($gatewayConfigured) {
    foreach ($accountRows as $r) {
        $st = wa_check_status($conn, $r['account_id']);
        $liveStatuses[$r['account_id']] = $st['ok'] ? $st['status'] : $r['status'];
        if ($st['ok'] && $st['status'] !== $r['status']) {
            $conn->query("UPDATE whatsapp_accounts SET status = '" . mysqli_real_escape_string($conn, $st['status']) . "' WHERE account_id = '" . mysqli_real_escape_string($conn, $r['account_id']) . "'");
        }
    }
}

$connectingId = $_GET['connecting'] ?? null;
$connectingMethod = $_GET['method'] ?? 'qr';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root{ --p:#25D366; --p2:#128C7E; --g: linear-gradient(135deg,#25D366,#128C7E); }
    .wa-card{background:#14141f;border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:24px;margin-bottom:20px}
    .wa-card h3{margin:0 0 14px;font-size:1.05rem;color:#fff}
    .wa-form-group{margin-bottom:14px}
    .wa-form-group label{display:block;font-size:.8rem;color:rgba(255,255,255,.6);margin-bottom:6px}
    .wa-form-group input,.wa-form-group select,.wa-form-group textarea{width:100%;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:10px 12px;color:#fff;font-size:.9rem}
    .wa-btn{background:var(--g);border:none;color:#fff;font-weight:700;padding:10px 20px;border-radius:8px;cursor:pointer;font-size:.85rem}
    .wa-btn.danger{background:#e04e4e}
    .wa-msg{border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.85rem}
    .wa-msg.success{background:rgba(37,211,102,.12);color:#25D366}
    .wa-msg.error{background:rgba(255,101,132,.12);color:#ff6584}
    .wa-account-row{display:flex;align-items:center;justify-content:space-between;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06);border-radius:10px;padding:14px 16px;margin-bottom:10px}
    .wa-status{font-size:.72rem;font-weight:700;padding:3px 10px;border-radius:20px}
    .wa-status.connected{background:rgba(37,211,102,.15);color:#25D366}
    .wa-status.qr_ready,.wa-status.code_ready,.wa-status.connecting,.wa-status.reconnecting{background:rgba(245,185,59,.15);color:#f5b93b}
    .wa-status.disconnected,.wa-status.error,.wa-status.not_started{background:rgba(255,101,132,.15);color:#ff6584}
    .wa-qr-box{text-align:center;padding:24px;background:#fff;border-radius:12px;margin-top:14px}
    .wa-code-box{text-align:center;font-size:2rem;font-weight:800;letter-spacing:6px;color:#25D366;background:rgba(37,211,102,.08);border-radius:12px;padding:20px;margin-top:14px}
</style>

<div class="wa-card">
    <h3><i class="fab fa-whatsapp"></i> WhatsApp Gateway Connection</h3>
    <p style="font-size:.8rem;color:rgba(255,255,255,.45);margin:0 0 16px">Self-hosted Node.js gateway se connect karein (koi third-party service nahi). Setup instructions <code>whatsapp-gateway/README.md</code> me hain.</p>
    <?php if (!$gatewayConfigured): ?>
        <div class="wa-msg error">Gateway abhi connect nahi hai - URL aur API Key daal ke save karein.</div>
    <?php endif; ?>
    <form method="POST" action="">
        <div class="wa-form-group">
            <label>Gateway URL</label>
            <input type="text" name="gateway_url" placeholder="http://127.0.0.1:3300" value="<?php echo htmlspecialchars($settings['whatsapp_gateway_url'] ?? ''); ?>">
        </div>
        <div class="wa-form-group">
            <label>API Key</label>
            <input type="password" name="gateway_api_key" placeholder="<?php echo !empty($settings['whatsapp_gateway_api_key']) ? '•••••••• (saved - blank rehne dein badalna na ho to)' : 'Gateway ka GATEWAY_API_KEY value'; ?>">
        </div>
        <div class="wa-form-group" style="display:flex;align-items:center;gap:10px">
            <input type="checkbox" name="notifications_enabled" id="waEnabled" value="1" <?php echo (($settings['whatsapp_notifications_enabled'] ?? 1) == 1) ? 'checked' : ''; ?>>
            <label for="waEnabled" style="margin:0">WhatsApp notifications on rakho (OTP, login alert, reminders)</label>
        </div>
        <button type="submit" name="save_gateway" class="wa-btn"><i class="fas fa-floppy-disk"></i> Save</button>
    </form>
</div>

<div class="wa-card">
    <h3><i class="fas fa-plus"></i> Add WhatsApp Number</h3>
    <?php if ($message): ?><div class="wa-msg <?php echo $message['type']; ?>"><?php echo htmlspecialchars($message['text']); ?></div><?php endif; ?>
    <form method="POST" action="">
        <div class="wa-form-group">
            <label>Label</label>
            <input type="text" name="label" placeholder="Support Line 1" required>
        </div>
        <div class="wa-form-group">
            <label>Phone Number (country code ke saath, bina +)</label>
            <input type="text" name="phone_number" placeholder="919876543210" required>
        </div>
        <div class="wa-form-group">
            <label>Connect Via</label>
            <select name="method">
                <option value="qr">QR Code Scan</option>
                <option value="code">Pairing Code</option>
            </select>
        </div>
        <button type="submit" name="start_connect" class="wa-btn"><i class="fab fa-whatsapp"></i> Connect</button>
    </form>

    <?php if ($connectingId): ?>
    <div id="connectPanel" style="margin-top:20px;text-align:center">
        <p style="color:rgba(255,255,255,.6);font-size:.85rem">Status: <span id="connectStatusText">Waiting...</span></p>
        <div id="connectDisplay"></div>
    </div>
    <script>
        var accountId = <?php echo json_encode($connectingId); ?>;
        var pollInterval = setInterval(function(){
            fetch('whatsapp_status_check?account_id=' + encodeURIComponent(accountId))
                .then(r => r.json())
                .then(data => {
                    document.getElementById('connectStatusText').textContent = data.status || 'unknown';
                    var display = document.getElementById('connectDisplay');
                    if (data.status === 'qr_ready' && data.qr_data_url) {
                        display.innerHTML = '<div class="wa-qr-box"><img src="' + data.qr_data_url + '" style="max-width:260px"></div><p style="font-size:.78rem;color:rgba(255,255,255,.5);margin-top:10px">WhatsApp app me Settings -> Linked Devices -> Link a Device se scan karein</p>';
                    } else if (data.status === 'code_ready' && data.pairing_code) {
                        display.innerHTML = '<div class="wa-code-box">' + data.pairing_code + '</div><p style="font-size:.78rem;color:rgba(255,255,255,.5);margin-top:10px">WhatsApp app me Settings -> Linked Devices -> Link with phone number me yeh code daalein</p>';
                    } else if (data.status === 'connected') {
                        display.innerHTML = '<div style="color:#25D366;font-weight:700;padding:20px"><i class="fas fa-circle-check"></i> Connected!</div>';
                        clearInterval(pollInterval);
                        setTimeout(function(){ window.location.href = 'whatsapp_gateway'; }, 1500);
                    }
                });
        }, 2500);
    </script>
    <?php endif; ?>
</div>

<div class="wa-card">
    <h3><i class="fas fa-list"></i> Connected Accounts</h3>
    <?php if (empty($accountRows)): ?>
        <p style="color:rgba(255,255,255,.4);font-size:.85rem">Abhi koi number connect nahi hai.</p>
    <?php else: ?>
        <?php foreach ($accountRows as $r): $st = $liveStatuses[$r['account_id']] ?? $r['status']; ?>
        <div class="wa-account-row">
            <div>
                <div style="font-weight:700"><?php echo htmlspecialchars($r['label']); ?></div>
                <div style="font-size:.78rem;color:rgba(255,255,255,.45)"><?php echo htmlspecialchars($r['phone_number']); ?></div>
            </div>
            <div style="display:flex;align-items:center;gap:12px">
                <span class="wa-status <?php echo htmlspecialchars($st); ?>"><?php echo htmlspecialchars($st); ?></span>
                <form method="POST" action="" onsubmit="return confirm('Disconnect this number?')">
                    <input type="hidden" name="account_id" value="<?php echo htmlspecialchars($r['account_id']); ?>">
                    <button type="submit" name="disconnect_account" class="wa-btn danger"><i class="fas fa-unlink"></i></button>
                </form>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<div class="wa-card">
    <h3><i class="fas fa-paper-plane"></i> Send Manual Message</h3>
    <form method="POST" action="">
        <div class="wa-form-group">
            <label>To (phone number)</label>
            <input type="text" name="manual_to" placeholder="919876543210" required>
        </div>
        <div class="wa-form-group">
            <label>Message</label>
            <textarea name="manual_message" rows="4" placeholder="Type your message..." required></textarea>
        </div>
        <button type="submit" name="manual_send" class="wa-btn"><i class="fas fa-paper-plane"></i> Send</button>
    </form>
</div>
