<?php
include "header.php"; // header.php already includes config.php and provides $conn

// Initialize variables
$whatsapp_api_url = '';
$sender_id = '';
$api_key = '';
$sender_email = '';

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

    exit;
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Capture the POST data
    $whatsapp_api_url = $_POST['whatsapp_api_url'];
    $sender_id = $_POST['sender_id'];
    $api_key = $_POST['api_key'];
    $sender_email = $_POST['sender_email'];

    // Check if settings already exist
    $query = "SELECT * FROM api_settings LIMIT 1"; // Get any existing setting
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // If settings exist, update them
        $settings = $result->fetch_assoc();
        $id = $settings['id'];

        // Prepare the update statement
        $update_query = "UPDATE api_settings SET whatsapp_api_url = ?, sender_id = ?, api_key = ?, sender_email = ? WHERE id = ?";
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param("ssssi", $whatsapp_api_url, $sender_id, $api_key, $sender_email, $id);

        if ($update_stmt->execute()) {
            $message = 'API settings updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error updating settings: ' . $update_stmt->error;
            $messageType = 'error';
        }
        $update_stmt->close();
    } else {
        // If no settings exist, insert new ones
        $insert_query = "INSERT INTO api_settings (whatsapp_api_url, sender_id, api_key, sender_email) VALUES (?, ?, ?, ?)";
        $insert_stmt = $conn->prepare($insert_query);
        $insert_stmt->bind_param("ssss", $whatsapp_api_url, $sender_id, $api_key, $sender_email);

        if ($insert_stmt->execute()) {
            $message = 'API settings added successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error adding settings: ' . $insert_stmt->error;
            $messageType = 'error';
        }
        $insert_stmt->close();
    }

    // Redirect after form submission so the SweetAlert popup is triggered
    // *after* the SweetAlert2 library has actually loaded, instead of the
    // old inline <script>Swal.fire()</script> that ran before the library's
    // <script src="..."> tag at the bottom of the page — which meant the
    // success/error popup silently never appeared for the admin.
    header("Location: add_api.php?message=" . urlencode($message) . "&type=" . urlencode($messageType));
    exit();
}

// Fetch current API settings to display in the form if they exist
$query = "SELECT * FROM api_settings LIMIT 1"; // Get any existing setting
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $settings = $result->fetch_assoc();
    $whatsapp_api_url = $settings['whatsapp_api_url'];
    $sender_id = $settings['sender_id'];
    $api_key = $settings['api_key'];
    $sender_email = $settings['sender_email'];
} else {
    // No settings found, set default values
    $whatsapp_api_url = '';
    $sender_id = '';
    $api_key = '';
    $sender_email = '';
}

$stmt->close(); // Close the statement
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .aa-wrap{padding:20px;max-width:760px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .aa-head{margin-bottom:22px}
    .aa-head h1{font-size:1.5rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .aa-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .aa-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-body{padding:26px}

    .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    @media(max-width:600px){.form-grid{grid-template-columns:1fr}}
    .form-group{margin-bottom:18px}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:12px 14px;color:#fff;font-size:.9rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3)}

    .btn-primary-cta{
        width:100%;background:var(--g);border:none;color:#fff;padding:13px;border-radius:10px;
        font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);margin-top:6px;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}
</style>

<div class="aa-wrap">
    <div class="aa-head">
        <h1><span class="icn"><i class="fas fa-plug-circle-bolt"></i></span>WhatsApp API Settings</h1>
        <p>Credentials used to send WhatsApp payment notifications to customers</p>
    </div>

    <div class="glass-card">
        <div class="card-body">
            <form method="POST" action="">
                <div class="form-grid">
                    <div class="form-group" style="grid-column:1/-1">
                        <label class="form-label">WhatsApp API URL</label>
                        <input type="text" name="whatsapp_api_url" placeholder="https://wa.indiaapi.shop/send-message" value="<?php echo htmlspecialchars($whatsapp_api_url); ?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Sender ID</label>
                        <input type="text" name="sender_id" placeholder="Eg. 6200218694" value="<?php echo htmlspecialchars($sender_id); ?>" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">API Key</label>
                        <input type="text" name="api_key" placeholder="Your API Key" value="<?php echo htmlspecialchars($api_key); ?>" class="form-control" required>
                    </div>
                    <div class="form-group" style="grid-column:1/-1">
                        <label class="form-label">Sender Email</label>
                        <input type="email" name="sender_email" placeholder="you@example.com" value="<?php echo htmlspecialchars($sender_email); ?>" class="form-control" required>
                    </div>
                </div>
                <button type="submit" class="btn-primary-cta"><i class="fas fa-floppy-disk"></i> Save Settings</button>
            </form>
        </div>
    </div>
</div>

<!-- Include necessary scripts -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<!-- PAGE LEVEL SCRIPTS-->
<script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script>
    <?php if (isset($_GET['message'])): ?>
    Swal.fire({
        title: '<?php echo ($_GET['type'] ?? 'success') === 'success' ? 'Success!' : 'Error!'; ?>',
        text: '<?php echo addslashes($_GET['message']); ?>',
        icon: '<?php echo ($_GET['type'] ?? 'success') === 'success' ? 'success' : 'error'; ?>',
        confirmButtonText: 'OK',
        background: '#14141f',
        color: '#fff'
    }).then(function() {
        var url = new URL(window.location.href);
        url.searchParams.delete('message');
        url.searchParams.delete('type');
        window.history.replaceState({}, document.title, url.toString());
    });
    <?php endif; ?>
</script>
</body>
</html>
