<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

define('DATA_DIR', __DIR__ . '/data');

function ensureDataDir() {
    if (!is_dir(DATA_DIR)) mkdir(DATA_DIR, 0755, true);
    if (!file_exists(DATA_DIR . '/.htaccess')) {
        file_put_contents(DATA_DIR . '/.htaccess', "Deny from all\n");
    }
}

function loadData($file) {
    ensureDataDir();
    $path = DATA_DIR . '/' . $file;
    if (!file_exists($path)) return [];
    $raw = file_get_contents($path);
    return json_decode($raw, true) ?: [];
}

function saveData($file, $data) {
    ensureDataDir();
    $path = DATA_DIR . '/' . $file;
    file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOCK_EX);
}

// Prepare Data for Form
$allAppsForAdmin = loadData('applications.json');
usort($allAppsForAdmin, function($a,$b){ return ($a['sort_order']??0) - ($b['sort_order']??0); });

$APP_LABELS = []; $APP_MAX = []; $APP_URLS_PHP = [];
foreach ($allAppsForAdmin as $app) {
    if ($app['is_active']) {
        $APP_LABELS[$app['id']] = $app['name'];
        $APP_MAX[$app['id']] = (int)$app['max_servers'];
        $APP_URLS_PHP[$app['id']] = $app['default_url'] ?? '';
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Inject Cookies - TEXA Apps</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--deep:#020c18;--blue:#0066ff;--bright:#0099ff;--light:#4db8ff;--text:#e8f4ff;--sub:#7aaed4;--muted:#4a7a9b;--glass:rgba(4,22,48,.85);--border:rgba(0,150,255,.18);--ok:#00e676;--err:#ff4d4d;--warn:#ffaa00}
body{min-height:100vh;background:var(--deep);font-family:"Inter",sans-serif;color:var(--text)}
body::before{content:"";position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at 15% 15%,rgba(0,80,180,.22) 0%,transparent 55%),radial-gradient(ellipse at 85% 85%,rgba(0,40,130,.16) 0%,transparent 55%)}
.wrap{max-width:940px;margin:0 auto;padding:28px 18px;position:relative;z-index:1}
.hdr{display:flex;align-items:center;gap:14px;margin-bottom:26px}
.logo{width:46px;height:46px;border-radius:13px;background:linear-gradient(135deg,#0044cc,#0099ff);display:flex;align-items:center;justify-content:center;font-size:15px;font-weight:900;box-shadow:0 0 18px rgba(0,150,255,.4)}
.hdr-text h1{font-size:20px;font-weight:800;background:linear-gradient(135deg,#e0f0ff,#4db8ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.hdr-text p{font-size:12px;color:var(--sub);margin-top:3px}
.card{background:var(--glass);border:1px solid var(--border);border-radius:14px;padding:20px;margin-bottom:20px;box-shadow:0 8px 32px rgba(0,0,0,.4);backdrop-filter:blur(10px)}
.ct{font-size:15px;font-weight:700;margin-bottom:18px;color:#fff;display:flex;align-items:center;gap:8px}
.ct::before{content:"";width:4px;height:16px;background:var(--bright);border-radius:2px}
.fg{display:flex;flex-wrap:wrap;gap:14px}
.fi{flex:1 1 200px;min-width:200px}
.fi.full{flex:1 1 100%}
label{display:block;font-size:11px;font-weight:600;color:var(--sub);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
input[type="text"],input[type="number"],input[type="url"],select,textarea{width:100%;background:rgba(0,20,50,.4);border:1px solid var(--border);color:#fff;border-radius:8px;padding:10px 14px;font-size:13px;font-family:inherit;transition:all .2s;outline:none}
input:focus,select:focus,textarea:focus{border-color:var(--bright);box-shadow:0 0 0 3px rgba(0,150,255,.15)}
textarea{min-height:200px;resize:vertical;font-family:monospace;font-size:12px;line-height:1.4}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:10px 18px;font-size:13px;font-weight:600;border-radius:8px;border:none;cursor:pointer;transition:all .2s;text-decoration:none;font-family:inherit}
.bp{background:linear-gradient(135deg,#0066ff,#0099ff);color:#fff;box-shadow:0 4px 12px rgba(0,102,255,.3)}
.bp:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(0,102,255,.4);filter:brightness(1.1)}
</style>
</head>
<body>
<div class="wrap">
  <div class="hdr">
    <div class="logo">TX</div>
    <div class="hdr-text">
      <h1 id="page-title">TEXA Apps — Inject Cookies</h1>
      <p>Tempel JSON Payload dari J2TEAM / EditThisCookie</p>
    </div>
  </div>
  
  <div class="card">
    <div class="ct">Inject Cookies Server</div>
    <div id="c-form">
      <div class="fg">
        <div class="fi">
          <label>Pilih Aplikasi</label>
          <select id="c-app" required>
            <option value="">-- Pilih Aplikasi --</option>
            <?php foreach ($APP_LABELS as $aid => $lbl): ?>
              <option value="<?php echo $aid; ?>"><?php echo $lbl; ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="fi">
          <label>Pilih Server</label>
          <select id="c-server" required>
            <option value="">-- Pilih Server --</option>
          </select>
        </div>
        <div class="fi full" style="margin-top:10px;">
          <label>URL Tujuan Aplikasi (Opsional)</label>
          <input type="url" id="c-url" placeholder="Biarkan kosong jika tetap memakai URL bawaan" style="width:100%;box-sizing:border-box;margin-bottom:10px;">
          <label>Paste JSON Payload (J2TEAM / EditThisCookie)</label>
          <textarea id="c-data" placeholder='[{"name":"session_id","value":"xyz","domain":".google.com",...}]' required></textarea>
        </div>
        <div class="fi full">
           <div id="c-msg" style="font-size:12px;font-weight:bold;margin-top:5px;margin-bottom:5px;"></div>
        </div>
        <div class="fi full" style="display:flex;justify-content:flex-end;margin-top:4px">
          <button type="button" class="btn bp" id="c-submit-btn" onclick="saveC()">&#x1F4BE; Simpan & Inject Sessions</button>
        </div>
      </div>
    </div>
  </div>
  
  <p style="text-align:center;font-size:10px;color:var(--muted);opacity:.5;margin-top:30px">TEXA Apps Member Manager &copy; 2026</p>
</div>

<script>
const APP_MAX = <?php echo json_encode($APP_MAX); ?>;
document.getElementById('c-app').addEventListener('change', function() {
    const APP_URLS = <?php echo json_encode($APP_URLS_PHP); ?>;
    const srvSelect = document.getElementById('c-server');
    const urlInput = document.getElementById('c-url');
    srvSelect.innerHTML = '<option value="">-- Pilih Server --</option>';
    const max = APP_MAX[this.value] || 0;
    if (APP_URLS[this.value]) urlInput.value = APP_URLS[this.value]; else urlInput.value = '';
    for (let i = 1; i <= max; i++) {
        const opt = document.createElement('option');
        opt.value = i; opt.textContent = 'Server ' + i;
        srvSelect.appendChild(opt);
    }
});

// Deep-link preselection: ?app=<app_id>&server=<index>
window.addEventListener('DOMContentLoaded', () => {
    const params = new URLSearchParams(window.location.search);
    const appId = params.get('app');
    const serverIdx = params.get('server');
    const appSel = document.getElementById('c-app');
    const srvSel = document.getElementById('c-server');
    const urlInput = document.getElementById('c-url');
    const titleEl = document.getElementById('page-title');

    if (appId && appSel) {
        // Set app value if exists in options
        const hasOption = Array.from(appSel.options).some(o => o.value === appId);
        if (hasOption) {
            appSel.value = appId;
            // Trigger change to populate servers and default URL
            const evt = new Event('change', { bubbles: true });
            appSel.dispatchEvent(evt);
        }
    }
    if (serverIdx && srvSel) {
        // Wait a tick to ensure servers populated
        setTimeout(() => {
            const hasSrv = Array.from(srvSel.options).some(o => o.value === serverIdx);
            if (hasSrv) srvSel.value = serverIdx;
        }, 0);
    }

    // Update page title with selection context
    setTimeout(() => {
        const appLabel = appSel && appSel.value ? appSel.options[appSel.selectedIndex].textContent : '';
        const srvLabel = srvSel && srvSel.value ? ('Server ' + srvSel.value) : '';
        if (appLabel || srvLabel) {
            titleEl.textContent = 'TEXA Apps — Inject Cookies' + (appLabel ? (' · ' + appLabel) : '') + (srvLabel ? (' · ' + srvLabel) : '');
        }
        // Ensure URL input reflects default for selected app
        const APP_URLS = <?php echo json_encode($APP_URLS_PHP); ?>;
        if (appSel && appSel.value && APP_URLS[appSel.value]) {
            urlInput.value = APP_URLS[appSel.value];
        }
    }, 10);
});

async function saveC() {
    const btn = document.getElementById('c-submit-btn');
    const msg = document.getElementById('c-msg');
    const app_id = document.getElementById('c-app').value;
    const server_index = document.getElementById('c-server').value;
    const target_url = document.getElementById('c-url').value;
    const cookie_data = document.getElementById('c-data').value;
    if (!app_id || !server_index || !cookie_data) { msg.textContent = '❌ Mohon lengkapi parameter.'; msg.style.color = '#ff4d4d'; return; }
    msg.textContent = 'Menyimpan...'; msg.style.color = '#4db8ff'; btn.disabled = true;
    try {
        const fd = new FormData();
        fd.append('app_id', app_id); fd.append('server_index', server_index);
        fd.append('target_url', target_url); fd.append('cookie_data', cookie_data);
        const res = await fetch('index.php?action=save_cookies', { method: 'POST', body: fd });
        const data = await res.json();
        if(data.success) { msg.textContent = '✅ Berhasil! Data disimpan.'; msg.style.color = '#00e676'; document.getElementById('c-data').value = ''; }
        else { msg.textContent = '❌ Gagal: ' + (data.message || 'Error'); msg.style.color = '#ff4d4d'; }
    } catch(err) { msg.textContent = '❌ Error koneksi.'; msg.style.color = '#ff4d4d'; }
    finally { btn.disabled = false; setTimeout(() => { if(msg.textContent.includes('Berhasil')) msg.textContent=''; }, 5000); }
}

// Auto-save when cookies payload is pasted or typed
let __autoSaveTimer = null;
function scheduleAutoSave() {
    clearTimeout(__autoSaveTimer);
    __autoSaveTimer = setTimeout(() => {
        const app_id = document.getElementById('c-app').value;
        const server_index = document.getElementById('c-server').value;
        const cookie_data = document.getElementById('c-data').value;
        const msg = document.getElementById('c-msg');
        if (!cookie_data || cookie_data.trim().length < 5) return;
        if (!app_id || !server_index) { msg.textContent = '⚠️ Pilih Aplikasi dan Server terlebih dahulu untuk auto-simpan.'; msg.style.color = '#ffaa00'; return; }
        saveC();
    }, 400);
}
const cDataEl = document.getElementById('c-data');
['paste','input','drop'].forEach(ev => cDataEl.addEventListener(ev, scheduleAutoSave));
// If user selects app/server after pasting, try auto-save again
document.getElementById('c-app').addEventListener('change', () => {
    if (document.getElementById('c-data').value.trim().length > 0) scheduleAutoSave();
});
document.getElementById('c-server').addEventListener('change', () => {
    if (document.getElementById('c-data').value.trim().length > 0) scheduleAutoSave();
});
</script>
</body>
</html>
