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

// === SECURITY: Require admin login ===
// Force session cookie path = '/' (see index.php for full explanation)
if (session_status() === PHP_SESSION_NONE) {
    $cp = session_get_cookie_params();
    session_set_cookie_params([
        'lifetime' => $cp['lifetime'] ?? 0,
        'path'     => '/',
        'domain'   => $cp['domain'] ?? '',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
    session_name('PHPSESSID');
    session_start();
}
if (empty($_SESSION['admin_logged_in']) || empty($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

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

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

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

// === Action handlers ===
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $act = $_GET['ajax'];

    if ($act === 'delete_project') {
        $code = trim($_POST['code'] ?? '');
        $url = trim($_POST['url'] ?? '');
        if (empty($code) || empty($url)) { echo json_encode(['success'=>false,'reason'=>'missing']); exit(); }
        $data = loadData('user_projects.json');
        if (isset($data[$code])) {
            $data[$code] = array_values(array_filter($data[$code], function($p) use ($url) {
                return $p['url'] !== $url;
            }));
            saveData('user_projects.json', $data);
        }
        echo json_encode(['success'=>true]); exit();
    }

    if ($act === 'clear_user') {
        $code = trim($_POST['code'] ?? '');
        if (empty($code)) { echo json_encode(['success'=>false]); exit(); }
        $data = loadData('user_projects.json');
        unset($data[$code]);
        saveData('user_projects.json', $data);
        echo json_encode(['success'=>true]); exit();
    }
    exit();
}

$userProjects = loadData('user_projects.json');
$members = loadData('members.json');
$memberMap = [];
foreach ($members as $m) {
    $memberMap[$m['code']] = $m;
}

// Stats
$totalUsers = count($userProjects);
$totalProjects = 0;
foreach ($userProjects as $list) $totalProjects += count($list);

// Filter & search
$searchQuery = trim($_GET['q'] ?? '');
$serverFilter = trim($_GET['server'] ?? '');
$packageFilter = trim($_GET['package'] ?? '');

$allServers = [];
foreach ($userProjects as $list) {
    foreach ($list as $p) {
        if (!empty($p['server_name']) && !in_array($p['server_name'], $allServers)) {
            $allServers[] = $p['server_name'];
        }
    }
}
sort($allServers);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>User Projects Admin - TEKNO-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;--purple:#a855f7}
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%);z-index:0}
.wrap{max-width:1280px;margin:0 auto;padding:28px 18px;position:relative;z-index:1}
.hdr{display:flex;align-items:center;gap:14px;margin-bottom:26px;flex-wrap:wrap}
.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);flex-shrink:0}
.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}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:20px}
.stat{background:var(--glass);border:1px solid var(--border);border-radius:12px;padding:16px;display:flex;flex-direction:column;gap:4px}
.stat-label{font-size:11px;color:var(--sub);text-transform:uppercase;letter-spacing:.5px;font-weight:600}
.stat-value{font-size:24px;font-weight:800;color:#fff}
.stat-icon{font-size:20px}
.toolbar{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px;padding:14px;background:var(--glass);border:1px solid var(--border);border-radius:12px}
.toolbar input,.toolbar select{background:rgba(0,20,50,.5);border:1px solid var(--border);color:#fff;padding:8px 12px;border-radius:8px;font-size:13px;font-family:inherit;outline:none;flex:1;min-width:180px}
.toolbar input:focus,.toolbar select:focus{border-color:var(--bright);box-shadow:0 0 0 3px rgba(0,150,255,.15)}
.toolbar button{background:linear-gradient(135deg,#0066ff,#0099ff);color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600}
.user-card{background:var(--glass);border:1px solid var(--border);border-radius:12px;margin-bottom:14px;overflow:hidden}
.user-head{padding:14px 18px;display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:pointer;background:rgba(0,30,80,.3);transition:background .2s;flex-wrap:wrap}
.user-head:hover{background:rgba(0,50,120,.4)}
.user-info{display:flex;align-items:center;gap:14px;flex:1;min-width:200px}
.user-avatar{width:38px;height:38px;border-radius:9px;background:linear-gradient(135deg,#7c3aed,#a855f7);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;color:#fff;flex-shrink:0}
.user-meta{display:flex;flex-direction:column;gap:2px;min-width:0}
.user-code{font-size:14px;font-weight:600;color:#fff;word-break:break-all}
.user-name{font-size:11px;color:var(--sub)}
.user-tags{display:flex;gap:6px;flex-wrap:wrap}
.tag{font-size:10px;font-weight:600;padding:3px 8px;border-radius:4px;text-transform:uppercase;letter-spacing:.3px;white-space:nowrap}
.tag-pkg{background:rgba(168,85,247,.15);color:#c084fc;border:1px solid rgba(168,85,247,.3)}
.tag-active{background:rgba(0,230,118,.15);color:#00e676;border:1px solid rgba(0,230,118,.3)}
.tag-inactive{background:rgba(255,77,77,.15);color:#ff8080;border:1px solid rgba(255,77,77,.3)}
.tag-expired{background:rgba(255,170,0,.15);color:#ffcc44;border:1px solid rgba(255,170,0,.3)}
.tag-count{background:rgba(0,150,255,.15);color:var(--light);border:1px solid var(--border);font-weight:700}
.user-actions{display:flex;gap:6px;align-items:center}
.btn-sm{padding:6px 10px;font-size:11px;border-radius:6px;cursor:pointer;border:none;font-weight:600;font-family:inherit;transition:all .2s}
.btn-danger{background:rgba(255,77,77,.15);color:#ff8080;border:1px solid rgba(255,77,77,.3)}
.btn-danger:hover{background:#ff4d4d;color:#fff}
.btn-toggle{background:rgba(0,150,255,.15);color:var(--light);border:1px solid var(--border)}
.btn-toggle:hover{background:rgba(0,150,255,.3);color:#fff}
.user-projects{display:none;padding:14px 18px;background:rgba(0,10,30,.5);border-top:1px solid var(--border)}
.user-projects.open{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:10px}
.project{background:rgba(0,30,80,.4);border:1px solid var(--border);border-radius:8px;padding:12px;display:flex;flex-direction:column;gap:6px;transition:all .2s}
.project:hover{border-color:var(--bright);background:rgba(0,50,140,.5)}
.project-id{font-size:13px;font-weight:600;color:#fff;font-family:monospace;word-break:break-all;line-height:1.3}
.project-meta{display:flex;flex-wrap:wrap;gap:5px;font-size:10px}
.project-meta .tag{font-size:9px;padding:2px 6px}
.project-actions{display:flex;gap:6px;margin-top:4px}
.project-actions a,.project-actions button{flex:1;text-align:center;padding:5px 8px;font-size:10px;border-radius:5px;text-decoration:none;font-weight:600;transition:all .2s;border:none;cursor:pointer;font-family:inherit}
.btn-open{background:linear-gradient(135deg,#0066ff,#0099ff);color:#fff}
.btn-open:hover{filter:brightness(1.15)}
.btn-copy{background:rgba(0,30,80,.6);color:var(--light);border:1px solid var(--border)}
.btn-copy:hover{background:rgba(0,80,160,.6);color:#fff}
.btn-del-project{background:rgba(255,77,77,.15);color:#ff8080;border:1px solid rgba(255,77,77,.3)}
.btn-del-project:hover{background:#ff4d4d;color:#fff}
.empty{text-align:center;padding:40px 20px;color:var(--muted);font-size:13px}
.empty-icon{font-size:48px;margin-bottom:12px;opacity:.4}
.toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:var(--ok);color:#000;padding:10px 20px;border-radius:8px;font-size:13px;font-weight:600;opacity:0;transition:opacity .3s;pointer-events:none;z-index:9999}
.toast.show{opacity:1}
.toast.err{background:var(--err);color:#fff}
</style>
</head>
<body>
<div class="wrap">
  <div class="hdr">
    <div class="logo">TX</div>
    <div class="hdr-text">
      <h1>User Projects Admin</h1>
      <p>Daftar semua project Google Flow yang dibuat user</p>
    </div>
  </div>

  <div class="stats">
    <div class="stat">
      <div class="stat-label">Total Users</div>
      <div class="stat-value"><?php echo $totalUsers; ?> <span class="stat-icon">👥</span></div>
    </div>
    <div class="stat">
      <div class="stat-label">Total Projects</div>
      <div class="stat-value"><?php echo $totalProjects; ?> <span class="stat-icon">🎬</span></div>
    </div>
    <div class="stat">
      <div class="stat-label">Total Members Aktif</div>
      <div class="stat-value"><?php echo count(array_filter($members, function($m){return !empty($m['is_active']);})); ?> <span class="stat-icon">✅</span></div>
    </div>
    <div class="stat">
      <div class="stat-label">Avg Project / User</div>
      <div class="stat-value"><?php echo $totalUsers > 0 ? round($totalProjects/$totalUsers, 1) : 0; ?> <span class="stat-icon">📊</span></div>
    </div>
  </div>

  <form class="toolbar" method="GET">
    <input type="text" name="q" placeholder="🔍 Cari kode voucher / nama / project ID..." value="<?php echo htmlspecialchars($searchQuery); ?>"/>
    <select name="server">
      <option value="">📡 Semua Server</option>
      <?php foreach ($allServers as $s): ?>
        <option value="<?php echo htmlspecialchars($s); ?>" <?php echo $serverFilter === $s ? 'selected' : ''; ?>><?php echo htmlspecialchars($s); ?></option>
      <?php endforeach; ?>
    </select>
    <select name="package">
      <option value="">📦 Semua Paket</option>
      <option value="basic" <?php echo $packageFilter === 'basic' ? 'selected' : ''; ?>>Basic</option>
      <option value="pro" <?php echo $packageFilter === 'pro' ? 'selected' : ''; ?>>Pro</option>
      <option value="ultimate" <?php echo $packageFilter === 'ultimate' ? 'selected' : ''; ?>>Ultimate</option>
      <option value="trial" <?php echo $packageFilter === 'trial' ? 'selected' : ''; ?>>Trial</option>
      <option value="custom" <?php echo $packageFilter === 'custom' ? 'selected' : ''; ?>>Custom</option>
    </select>
    <button type="submit">Filter</button>
    <a href="user_projects_admin.php" style="padding:8px 16px;background:rgba(0,40,90,.5);color:var(--sub);border-radius:8px;text-decoration:none;font-size:13px;font-weight:600;align-self:center;">Reset</a>
  </form>

  <div id="users-list">
    <?php
    $rendered = 0;
    foreach ($userProjects as $code => $projects) {
        $member = $memberMap[$code] ?? null;
        $memberName = $member['name'] ?? '(unknown)';
        $package = $member['package'] ?? '-';
        $isActive = !empty($member['is_active']);
        $expiry = $member['expiry_date'] ?? null;
        $isExpired = $expiry && strtotime($expiry) < time();

        // Apply filters
        if ($searchQuery !== '') {
            $hayStack = strtolower($code . ' ' . $memberName);
            $matchesProject = false;
            foreach ($projects as $p) {
                if (stripos($p['url'], $searchQuery) !== false) { $matchesProject = true; break; }
            }
            if (stripos($hayStack, $searchQuery) === false && !$matchesProject) continue;
        }
        if ($packageFilter !== '' && $package !== $packageFilter) continue;
        if ($serverFilter !== '') {
            $hasServer = false;
            foreach ($projects as $p) {
                if (($p['server_name'] ?? '') === $serverFilter) { $hasServer = true; break; }
            }
            if (!$hasServer) continue;
        }

        $rendered++;
        $initials = strtoupper(substr($code, 0, 2));
        $countStr = count($projects) . '/10';
    ?>
    <div class="user-card" data-code="<?php echo htmlspecialchars($code); ?>">
      <div class="user-head" onclick="toggleProjects(this)">
        <div class="user-info">
          <div class="user-avatar"><?php echo htmlspecialchars($initials); ?></div>
          <div class="user-meta">
            <div class="user-code"><?php echo htmlspecialchars($code); ?></div>
            <div class="user-name"><?php echo htmlspecialchars($memberName); ?> · Expiry: <?php echo htmlspecialchars($expiry ?? '-'); ?></div>
          </div>
        </div>
        <div class="user-tags">
          <span class="tag tag-pkg"><?php echo htmlspecialchars($package); ?></span>
          <?php if ($isExpired): ?>
            <span class="tag tag-expired">EXPIRED</span>
          <?php elseif ($isActive): ?>
            <span class="tag tag-active">ACTIVE</span>
          <?php else: ?>
            <span class="tag tag-inactive">INACTIVE</span>
          <?php endif; ?>
          <span class="tag tag-count"><?php echo $countStr; ?></span>
        </div>
        <div class="user-actions" onclick="event.stopPropagation()">
          <button class="btn-sm btn-toggle" onclick="toggleProjects(this.closest('.user-card').querySelector('.user-head'))">▾ Toggle</button>
          <button class="btn-sm btn-danger" onclick="clearUser('<?php echo htmlspecialchars(addslashes($code)); ?>')">🗑️ Hapus Semua</button>
        </div>
      </div>
      <div class="user-projects">
        <?php
        // Sort projects by created_at desc
        usort($projects, function($a, $b) {
            return strtotime($b['created_at'] ?? 0) - strtotime($a['created_at'] ?? 0);
        });
        foreach ($projects as $p):
            $url = $p['url'] ?? '';
            $createdAt = $p['created_at'] ?? '';
            $serverName = $p['server_name'] ?? '';
            $payloadIdx = isset($p['payload_index']) ? (int)$p['payload_index'] : null;
            $parts = explode('/', rtrim($url, '/'));
            $projId = end($parts);
            $shortId = strlen($projId) > 30 ? substr($projId, 0, 30) . '...' : $projId;
            $fullUrl = 'https://labs.google' . $url;
            // Format date as WIB
            $dateDisplay = $createdAt;
            try {
                $dt = new DateTime($createdAt, new DateTimeZone('Asia/Jakarta'));
                $dateDisplay = $dt->format('d M Y H:i') . ' WIB';
            } catch (Exception $e) {}
        ?>
        <div class="project">
          <div class="project-id">🎬 <?php echo htmlspecialchars($shortId); ?></div>
          <div class="project-meta">
            <?php if ($serverName): ?>
              <span class="tag tag-pkg">📡 <?php echo htmlspecialchars($serverName); ?></span>
            <?php endif; ?>
            <?php if ($payloadIdx !== null): ?>
              <span class="tag tag-count">👤 Account <?php echo $payloadIdx + 1; ?></span>
            <?php endif; ?>
          </div>
          <div style="font-size:10px;color:var(--muted);"><?php echo htmlspecialchars($dateDisplay); ?></div>
          <div class="project-actions">
            <a class="btn-open" href="<?php echo htmlspecialchars($fullUrl); ?>" target="_blank">Buka</a>
            <button class="btn-copy" onclick="copyText(this, '<?php echo htmlspecialchars(addslashes($fullUrl)); ?>')">Copy URL</button>
            <button class="btn-del-project" onclick="deleteProject('<?php echo htmlspecialchars(addslashes($code)); ?>', '<?php echo htmlspecialchars(addslashes($url)); ?>', this)">✕</button>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php } if ($rendered === 0): ?>
    <div class="empty">
      <div class="empty-icon">📂</div>
      <div>Belum ada project / tidak ada hasil yang cocok dengan filter.</div>
    </div>
    <?php endif; ?>
  </div>

  <p style="text-align:center;font-size:10px;color:var(--muted);opacity:.5;margin-top:30px">TEKNO-APPS Project Manager &copy; 2026</p>
</div>

<div id="toast" class="toast"></div>

<script>
function toggleProjects(headEl) {
    const card = headEl.closest('.user-card');
    const list = card.querySelector('.user-projects');
    list.classList.toggle('open');
}

function showToast(msg, isErr) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.classList.toggle('err', !!isErr);
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 1800);
}

function copyText(btn, text) {
    const fallback = () => {
        const ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        try { document.execCommand('copy'); } catch(e) {}
        document.body.removeChild(ta);
    };
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).catch(fallback);
    } else { fallback(); }
    showToast('✓ URL disalin');
}

async function deleteProject(code, url, btn) {
    if (!confirm('Hapus project ini dari user?\n\n' + url)) return;
    const fd = new FormData();
    fd.append('code', code);
    fd.append('url', url);
    try {
        const res = await fetch('user_projects_admin.php?ajax=delete_project', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            btn.closest('.project').remove();
            showToast('✓ Project dihapus');
        } else {
            showToast('✗ Gagal hapus', true);
        }
    } catch (e) {
        showToast('✗ Error koneksi', true);
    }
}

async function clearUser(code) {
    if (!confirm('Hapus SEMUA project untuk voucher: ' + code + ' ?')) return;
    const fd = new FormData();
    fd.append('code', code);
    try {
        const res = await fetch('user_projects_admin.php?ajax=clear_user', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            const card = document.querySelector('.user-card[data-code="' + CSS.escape(code) + '"]');
            if (card) card.remove();
            showToast('✓ Semua project user dihapus');
        } else {
            showToast('✗ Gagal hapus', true);
        }
    } catch (e) {
        showToast('✗ Error koneksi', true);
    }
}
</script>
</body>
</html>
