<?php
include 'ser.php';
$config = include 'config.php';
$expiration_config = include 'expiration_config.php';

if ($expiration_config && isset($expiration_config['expiration_datetime'])) {
    $expiration_date_str = $expiration_config['expiration_datetime'];

    if (!empty($expiration_date_str)) {
        $expiration_datetime = new DateTime($expiration_date_str);
        $current_time = new DateTime();

        if ($current_time > $expiration_datetime) {
            header('Location: exp.php');
            exit;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>ForxzZHost - Panel</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- Google Font (Poppins) -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">

    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #1cc88a;
            --dark-color: #2c3e50;
            --light-color: #ffffff;
            --accent-color: #f6c23e;
            --danger-color: #e74a3b;
        }

        /* FULL BACKGROUND IMAGE (NO DARK OVERLAY) */
        body {
            font-family: 'Poppins', sans-serif;
            background: url('https://files.catbox.moe/vanz8w.jp') no-repeat center center fixed;
            background-size: cover;
            background-attachment: fixed;
            color: var(--light-color);
            min-height: 100vh;
            padding: 0;
            margin: 0;
        }

        /* Container */
        .main-container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 2rem;
            animation: fadeIn 0.8s ease-out;
        }

        /* CARD GLASS EFFECT */
        .card {
            background: rgba(0, 0, 0, 0.25);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.25);
            border-radius: 12px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.45);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
        }

        .card-header {
            background: rgba(0, 0, 0, 0.35);
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            padding: 1.25rem 1.5rem;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .card-body {
            padding: 1.5rem;
        }

        .logo-container {
            text-align: center;
            margin-bottom: 2rem;
        }

        .logo-img {
            max-width: 220px;
            height: auto;
            filter: drop-shadow(0 5px 15px rgba(0, 0, 0, 0.3));
        }

        .form-control {
            background-color: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: #fff;
            border-radius: 8px;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }

        .form-control::placeholder {
            color: rgba(255, 255, 255, 0.65);
        }

        .form-control:focus {
            background-color: rgba(255, 255, 255, 0.18);
            border-color: var(--primary-color);
            box-shadow: none;
            color: #fff;
        }

        .btn {
            border-radius: 8px;
            padding: 12px 20px;
            font-weight: 500;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
            border: none;
            text-transform: uppercase;
            font-size: 0.85rem;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: #fff;
        }

        .btn-primary:hover {
            background-color: #3a5bd0;
            transform: translateY(-2px);
        }

        .btn-success {
            background-color: var(--secondary-color);
            color: #fff;
        }

        .btn-success:hover {
            background-color: #17a673;
            transform: translateY(-2px);
        }

        .btn-danger {
            background-color: var(--danger-color);
            color: #fff;
        }

        .btn-danger:hover {
            background-color: #d62c1a;
            transform: translateY(-2px);
        }

        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
        }

        .table {
            background: rgba(0, 0, 0, 0.35);
            color: #fff;
            margin-bottom: 0;
        }

        .table th {
            background: rgba(0, 0, 0, 0.45);
            border-bottom: 2px solid rgba(255, 255, 255, 0.06);
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.8rem;
            padding: 1rem;
        }

        .table td {
            border-top: 1px solid rgba(255, 255, 255, 0.03);
            padding: 0.75rem 1rem;
            vertical-align: middle;
        }

        .table tr:hover td {
            background-color: rgba(255, 255, 255, 0.04);
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-active {
            background-color: var(--secondary-color);
            box-shadow: 0 0 10px var(--secondary-color);
        }

        .action-btn {
            padding: 6px 12px;
            font-size: 0.8rem;
            border-radius: 6px;
        }

        .input-group-text {
            background-color: rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.15);
            color: white;
        }

        .section-title {
            font-weight: 600;
            margin-bottom: 1.5rem;
            position: relative;
            display: inline-block;
        }

        .section-title:after {
            content: '';
            position: absolute;
            bottom: -8px;
            left: 0;
            width: 50px;
            height: 3px;
            background: var(--primary-color);
            border-radius: 3px;
        }

        .badge {
            padding: 5px 10px;
            border-radius: 50px;
            font-weight: 500;
            font-size: 0.75rem;
        }

        .badge-primary {
            background-color: var(--primary-color);
        }

        .badge-success {
            background-color: var(--secondary-color);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .floating {
            animation: floating 3s ease-in-out infinite;
        }

        @keyframes floating {
            0% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
            100% { transform: translateY(0px); }
        }

        .glass-effect {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* Responsive tweaks */
        @media (max-width: 767px) {
            .main-container {
                padding: 1rem;
            }
            .card-header, .card-body {
                padding: 1rem;
            }
            .btn { padding: 10px 14px; font-size: 0.8rem; }
        }

        /* small clickable hint for autoplay fallback */
        #audio-unblock-hint {
            position: fixed;
            right: 12px;
            bottom: 12px;
            background: rgba(0,0,0,0.6);
            color: #fff;
            padding: 8px 12px;
            border-radius: 10px;
            font-size: 12px;
            display: none;
            z-index: 9999;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- Main Panel Card -->
        <div class="card animate__animated animate__fadeIn">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-cog mr-2"></i>Panel Configuration</span>
                <span class="badge badge-success"><i class="fas fa-circle status-indicator status-active"></i> Active</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <h5 class="section-title">Panel Settings</h5>
                        <div class="form-group">
                            <label for="namaResult">Nama Result</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                </div>
                                <input type="text" id="namaResult" class="form-control" value="<?= htmlspecialchars($nik, ENT_QUOTES); ?>">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="panelMurni">Nick Sender</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-server"></i></span>
                                </div>
                                <input type="text" id="panelMurni" class="form-control" value="<?= htmlspecialchars($sender, ENT_QUOTES); ?>" readonly>
                            </div>
                        </div>

                        <button id="gantiButton" class="btn btn-primary btn-block mt-4">
                            <i class="fas fa-sync-alt mr-2"></i>Update Data
                        </button>

                        <button id="whatsappButton" class="btn btn-block mt-3"
                            style="text-decoration: none;
                                   color: #fff;
                                   background: linear-gradient(45deg, #ff00ff, #ff9900, #00ff00, #0099ff);
                                   padding: 0.3em 0.4em;
                                   border-radius: 5px;
                                   border: 2px solid #fff;
                                   margin: 5px auto;
                                   display: inline-block;"
                            onclick="window.open('https://chat.whatsapp.com/BgU5FBsxgx33I5MYLfbdIS?mode=gi_t')">
                            <i class=""></i> Info Ladang Jasteb Vip Mas ForxzZHost Klik
                        </button>
                    </div>

                    <div class="col-md-6">
                        <h5 class="section-title">Add New Email</h5>
                        <div class="form-group">
                            <label for="email">Masukan Emailmu</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                </div>
                                <input type="email" id="email" name="email" class="form-control" placeholder="example@gmail.com" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="jumlahResult">Jumlah Result</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                                </div>
                                <input type="number" id="jumlahResult" name="jumlahResult" class="form-control" value="1" min="1" required>
                            </div>
                        </div>

                        <button id="addEmailButton" class="btn btn-success btn-block mt-4">
                            <i class="fas fa-plus-circle mr-2"></i>Add Email
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Email List Card -->
        <div class="card animate__animated animate__fadeIn animate__delay-1s">
            <div class="card-header">
                <i class="fas fa-list mr-2"></i>Email Management
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="emailTable" class="table table-hover">
                        <thead>
                            <tr>
                                <th><i class="fas fa-envelope mr-2"></i>Email</th>
                                <th><i class="fas fa-list-ol mr-2"></i>Jumlah Result</th>
                                <th><i class="fas fa-cogs mr-2"></i>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="emailData">
                            <!-- Data akan di-load via AJAX -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- AUDIO: background music autoplay (best-effort) -->
    <audio id="bgm" autoplay loop>
        <source src="https://files.catbox.moe/gldial.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
    <div id="audio-unblock-hint" title="Klik untuk mengaktifkan suara">Klik untuk mengaktifkan musik</div>

    <!-- Scripts (jQuery, Popper, Bootstrap) -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <!-- SweetAlert2 (JS) -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.all.min.js"></script>

    <script>
        $(document).ready(function() {
            // Initialize tooltips (kalau ada)
            $('[data-toggle="tooltip"]').tooltip();

            // Load emails on page load
            fetchEmails();

            // Try to autoplay background music and handle browser blocks
            const audio = document.getElementById('bgm');
            audio.volume = 0.25; // volume 25%
            // Attempt play: many browsers block autoplay with sound; handle fallback
            audio.play().then(() => {
                // autoplay succeeded
                $('#audio-unblock-hint').hide();
            }).catch(() => {
                // autoplay blocked — show hint and play on first user interaction
                $('#audio-unblock-hint').show();
                const unblock = () => {
                    audio.play().catch(() => {});
                    $('#audio-unblock-hint').hide();
                    document.removeEventListener('click', unblock);
                };
                // try once on click anywhere
                document.addEventListener('click', unblock, { once: true });
                // also allow clicking the hint itself
                $('#audio-unblock-hint').on('click', function(e) {
                    e.stopPropagation();
                    audio.play().catch(() => {});
                    $(this).hide();
                });
            });

            // Update data button click
            $('#gantiButton').click(function() {
                const namaResult = $('#namaResult').val().trim();
                const panelMurni = $('#panelMurni').val().trim();

                if (!namaResult || !panelMurni) {
                    Swal.fire({
                        title: 'Validation Error',
                        text: 'Name and Panel fields cannot be empty',
                        icon: 'error',
                        confirmButtonColor: '#4e73df'
                    });
                    return;
                }

                gantiNamaResult(namaResult, panelMurni);
            });

            // Add email button click
            $('#addEmailButton').click(function() {
                const email = $('#email').val().trim();
                const jumlahResult = $('#jumlahResult').val().trim();

                if (!email || !jumlahResult) {
                    Swal.fire({
                        title: 'Field Kosong',
                        text: 'Email dan Jumlah Result harus diisi.',
                        icon: 'error',
                        confirmButtonColor: '#4e73df'
                    });
                    return;
                }

                // CEK APAKAH EMAIL GMAIL
                if (!validateEmail(email)) {
                    Swal.fire({
                        title: 'Email Tidak Valid',
                        text: 'Hanya email dengan @gmail.com yang diperbolehkan.',
                        icon: 'error',
                        confirmButtonColor: '#e74a3b'
                    });
                    return;
                } else {
                    Swal.fire({
                        title: 'Email Valid!',
                        text: 'Email menggunakan @gmail.com',
                        icon: 'success',
                        confirmButtonColor: '#1cc88a',
                        timer: 1200,
                        showConfirmButton: false
                    });
                }

                addEmail(email, jumlahResult);
            });
        });

        function validateEmail(email) {
            return email.toLowerCase().endsWith('@gmail.com');
        }

        function gantiNamaResult(namaResult, panelMurni) {
            $.ajax({
                url: `ganti.php?nick=${encodeURIComponent(namaResult)}&sender=${encodeURIComponent(panelMurni)}`,
                method: 'GET',
                dataType: 'json',
                beforeSend: function() {
                    $('#gantiButton').html('<i class="fas fa-spinner fa-spin mr-2"></i> Updating...');
                    $('#gantiButton').prop('disabled', true);
                },
                success: function(data) {
                    $('#gantiButton').html('<i class="fas fa-sync-alt mr-2"></i> Update Data');
                    $('#gantiButton').prop('disabled', false);

                    if (data && data.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: data.message || 'Data berhasil diperbarui.',
                            icon: 'success',
                            confirmButtonColor: '#4e73df',
                            timer: 2000,
                            timerProgressBar: true,
                            willClose: () => {
                                location.reload();
                            }
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: (data && data.message) ? data.message : 'Gagal memperbarui data',
                            icon: 'error',
                            confirmButtonColor: '#4e73df'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('#gantiButton').html('<i class="fas fa-sync-alt mr-2"></i> Update Data');
                    $('#gantiButton').prop('disabled', false);
                    console.error('Error:', error);
                    Swal.fire({
                        title: 'Connection Error',
                        text: 'Failed to update data. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#4e73df'
                    });
                }
            });
        }

        function fetchEmails() {
            $.ajax({
                url: 'data.php',
                method: 'GET',
                dataType: 'json',
                beforeSend: function() {
                    $('#emailData').html('<tr><td colspan="3" class="text-center"><i class="fas fa-spinner fa-spin mr-2"></i> Loading emails...</td></tr>');
                },
                success: function(data) {
                    if (!data || data.length === 0) {
                        $('#emailData').html('<tr><td colspan="3" class="text-center">No emails found</td></tr>');
                        return;
                    }

                    let html = '';
                    data.forEach(item => {
                        // sanitize output minimally (client-side). Server must also sanitize.
                        const email = $('<div>').text(item.email).html();
                        const jumlah = $('<div>').text(item.jumlahResult).html();

                        html += `
                            <tr>
                                <td>${email}</td>
                                <td>${jumlah}</td>
                                <td>
                                    <button class="btn btn-danger btn-sm action-btn" onclick="deleteEmail('${email}')">
                                        <i class="fas fa-trash-alt mr-1"></i> Delete
                                    </button>
                                </td>
                            </tr>
                        `;
                    });
                    $('#emailData').html(html);
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching emails:', error);
                    $('#emailData').html('<tr><td colspan="3" class="text-center text-danger">Error loading emails</td></tr>');
                }
            });
        }

        function addEmail(email, jumlahResult) {
            const formData = new FormData();
            formData.append('email', email);
            formData.append('jumlahResult', jumlahResult);

            $.ajax({
                url: 'add.php',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#addEmailButton').html('<i class="fas fa-spinner fa-spin mr-2"></i> Adding...');
                    $('#addEmailButton').prop('disabled', true);
                },
                success: function(data) {
                    $('#addEmailButton').html('<i class="fas fa-plus-circle mr-2"></i> Add Email');
                    $('#addEmailButton').prop('disabled', false);

                    if (data && data.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: data.message || 'Email ditambahkan.',
                            icon: 'success',
                            confirmButtonColor: '#4e73df',
                            timer: 1500,
                            timerProgressBar: true
                        }).then(() => {
                            $('#email').val('');
                            $('#jumlahResult').val('1');
                            fetchEmails();
                        });
                    } else {
                        Swal.fire({
                            title: 'Success',
                            text: (data && data.message) ? data.message : 'Sukses menambahkan email',
                            icon: 'success',
                            confirmButtonColor: '#4e73df'
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('#addEmailButton').html('<i class="fas fa-plus-circle mr-2"></i> Add Email');
                    $('#addEmailButton').prop('disabled', false);
                    console.error('Error adding email:', error);
                    Swal.fire({
                        title: 'Connection Error',
                        text: 'Failed to add email. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#4e73df'
                    });
                }
            });
        }

        function deleteEmail(email) {
            Swal.fire({
                title: 'Confirm Deletion',
                text: `Are you sure you want to delete ${email}?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#1cc88a',
                cancelButtonColor: '#e74a3b',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'delete.php',
                        method: 'POST',
                        data: { email: email },
                        dataType: 'json',
                        success: function(data) {
                            Swal.fire({
                                title: data && data.success ? 'Deleted!' : 'Sukses',
                                text: (data && data.message) ? data.message : (data && data.success ? 'Deleted' : 'Failed to delete'),
                                icon: data && data.success ? 'success' : 'error',
                                confirmButtonColor: '#4e73df',
                                timer: 1500,
                                timerProgressBar: true
                            }).then(() => {
                                fetchEmails();
                            });
                        },
                        error: function(xhr, status, error) {
                            console.error('Error deleting email:', error);
                            Swal.fire({
                                title: 'Success',
                                text: 'Failed to delete email. Please try again.',
                                icon: 'success',
                                confirmButtonColor: '#4e73df'
                            });
                        }
                    });
                }
            });
        }
    </script>
</body>
</html>