<?php
session_start();
include 'config.php';

// --- 1. LOGIKA TRACKING PENGUNJUNG ---
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d');

$check_visitor = mysqli_query($conn, "SELECT * FROM visitor_stats WHERE ip_address='$ip' AND visit_date='$date'");
if (mysqli_num_rows($check_visitor) == 0) {
    mysqli_query($conn, "INSERT INTO visitor_stats (ip_address, visit_date) VALUES ('$ip', '$date')");
} else {
    mysqli_query($conn, "UPDATE visitor_stats SET last_activity=NOW() WHERE ip_address='$ip' AND visit_date='$date'");
}

$total_hits = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM visitor_stats"))['total'];
$today_hits = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM visitor_stats WHERE visit_date='$date'"))['total'];
$online_hits = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM visitor_stats WHERE last_activity > NOW() - INTERVAL 5 MINUTE"))['total'];

// --- 2. LOGIKA LOGIN & LOGOUT ---
if (isset($_POST['login'])) {
    $u = mysqli_real_escape_string($conn, $_POST['user']);
    $p = $_POST['pass'];
    $q = mysqli_query($conn, "SELECT * FROM admin_users WHERE username='$u' AND password='$p'");
    if(mysqli_num_rows($q) > 0){ 
        $_SESSION['admin'] = true; 
    } else {
        $error = "Username atau Password salah!";
    }
}

if (isset($_GET['logout'])) { 
    session_destroy(); 
    header("Location: masukpakadmingas.php"); 
    exit; 
}

if (!isset($_SESSION['admin'])) {
    echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Login Admin</title><script src="https://cdn.tailwindcss.com"></script></head>
    <body class="bg-[#0f172a] flex items-center justify-center h-screen p-4">
    <form method="post" class="bg-white p-8 rounded-[2rem] w-full max-w-sm shadow-2xl shadow-blue-500/20">
        <div class="text-center mb-8">
            <h2 class="text-3xl font-black text-slate-800 tracking-tighter italic">ADMIN<span class="text-blue-600">PANEL</span></h2>
            <p class="text-gray-400 text-xs font-bold uppercase tracking-widest mt-1">Sercerp3d Secure Login</p>
        </div>
        '.(isset($error) ? '<div class="bg-red-50 text-red-500 text-[10px] font-bold p-3 rounded-xl mb-4 text-center uppercase tracking-wider">'.$error.'</div>' : '').'
        <div class="space-y-4">
            <input type="text" name="user" placeholder="Username" class="w-full p-4 bg-gray-50 border-none rounded-2xl outline-none focus:ring-2 focus:ring-blue-500 transition-all font-medium" required>
            <input type="password" name="pass" placeholder="Password" class="w-full p-4 bg-gray-50 border-none rounded-2xl outline-none focus:ring-2 focus:ring-blue-500 transition-all font-medium" required>
            <button type="submit" name="login" class="w-full bg-blue-600 text-white py-4 rounded-2xl font-black shadow-lg shadow-blue-200 hover:bg-blue-700 hover:-translate-y-1 transition-all uppercase tracking-tighter">MASUK SEKARANG</button>
        </div>
    </form></body></html>'; 
    exit;
}

// --- 3. LOGIKA CRUD ---
if (isset($_GET['hapus'])) { 
    $id = intval($_GET['hapus']); 
    $data = mysqli_fetch_assoc(mysqli_query($conn, "SELECT image_url FROM fashion_products WHERE id='$id'"));
    if($data && file_exists($data['image_url'])) { unlink($data['image_url']); }
    mysqli_query($conn, "DELETE FROM fashion_products WHERE id='$id'"); 
    header("Location: masukpakadmingas.php"); 
    exit;
}

if (isset($_POST['simpan'])) {
    $id = $_POST['id'];
    $t  = mysqli_real_escape_string($conn, $_POST['title']);
    $s  = strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $t));
    $p  = intval($_POST['price']); 
    $l  = mysqli_real_escape_string($conn, $_POST['link']); 
    $d  = mysqli_real_escape_string($conn, $_POST['desc']); 
    $c  = $_POST['cat']; 
    $plat = $_POST['plat'];
    
    $image_path = $_POST['old_img']; 
    if ($_FILES['img_file']['name'] != "") {
        $target_dir = "uploads/";
        if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
        $file_ext = pathinfo($_FILES["img_file"]["name"], PATHINFO_EXTENSION);
        $new_filename = $s . "-" . time() . "." . $file_ext; 
        $target_file = $target_dir . $new_filename;
        if (move_uploaded_file($_FILES["img_file"]["tmp_name"], $target_file)) { $image_path = $target_file; }
    }

    if($id == ""){ 
        mysqli_query($conn, "INSERT INTO fashion_products (title, slug, price, image_url, affiliate_link, description, category, platform) VALUES ('$t','$s','$p','$image_path','$l','$d','$c','$plat')"); 
    } else { 
        mysqli_query($conn, "UPDATE fashion_products SET title='$t', slug='$s', price='$p', image_url='$image_path', affiliate_link='$l', description='$d', category='$c', platform='$plat' WHERE id='$id'"); 
    }
    header("Location: masukpakadmingas.php");
    exit;
}

$e = null; 
if(isset($_GET['edit'])){ 
    $id_e = intval($_GET['edit']); 
    $e = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM fashion_products WHERE id='$id_e'")); 
}
$search = isset($_GET['q']) ? mysqli_real_escape_string($conn, $_GET['q']) : '';
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Admin | Serverp3d</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>body { font-family: 'Plus Jakarta Sans', sans-serif; }</style>
</head>
<body class="bg-[#f8fafc] text-slate-900 pb-28 md:pb-10">

    <div class="max-w-5xl mx-auto px-4 pt-6">
        
        <div class="flex justify-between items-center mb-8 bg-white p-5 rounded-[2rem] shadow-sm border border-slate-100">
            <div>
                <h1 class="text-2xl font-black tracking-tighter italic text-slate-800">SERVERP<span class="text-blue-600">3D</span></h1>
                <p class="text-[9px] font-extrabold text-blue-500 uppercase tracking-[0.2em]">Store Management System</p>
            </div>
            <div class="flex items-center gap-3">
                <a href="?logout=true" class="bg-red-50 text-red-500 p-3 rounded-2xl hover:bg-red-500 hover:text-white transition-all group">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" /></svg>
                </a>
            </div>
        </div>

        <div class="grid grid-cols-3 gap-4 mb-8">
            <div class="bg-white p-5 rounded-[2.5rem] shadow-sm border border-slate-50 relative overflow-hidden group">
                <div class="absolute -right-2 -top-2 w-16 h-16 bg-blue-50 rounded-full group-hover:scale-150 transition-transform duration-500"></div>
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest relative">Total</p>
                <h4 class="text-2xl font-black text-slate-800 relative"><?php echo number_format($total_hits); ?></h4>
            </div>
            <div class="bg-blue-600 p-5 rounded-[2.5rem] shadow-lg shadow-blue-200 relative overflow-hidden">
                <p class="text-[10px] font-bold text-blue-100 uppercase tracking-widest relative">Today</p>
                <h4 class="text-2xl font-black text-white relative"><?php echo number_format($today_hits); ?></h4>
            </div>
            <div class="bg-white p-5 rounded-[2.5rem] shadow-sm border border-slate-50 text-center">
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Active</p>
                <div class="flex items-center justify-center gap-2">
                    <span class="w-2.5 h-2.5 bg-green-500 rounded-full animate-ping"></span>
                    <h4 class="text-2xl font-black text-slate-800"><?php echo number_format($online_hits); ?></h4>
                </div>
            </div>
        </div>

        <div class="grid md:grid-cols-5 gap-8">
            <div class="md:col-span-2">
                <section class="bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 sticky top-6">
                    <h3 class="text-lg font-black text-slate-800 mb-6 flex items-center gap-2 uppercase tracking-tighter">
                        <?php echo $e ? "📝 Edit Item" : "✨ New Product"; ?>
                    </h3>
                    <form method="post" enctype="multipart/form-data" class="space-y-5">
                        <input type="hidden" name="id" value="<?php echo $e['id']??''; ?>">
                        <input type="hidden" name="old_img" value="<?php echo $e['image_url']??''; ?>">
                        
                        <div class="space-y-1">
                            <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Product Title</label>
                            <input type="text" name="title" value="<?php echo $e['title']??''; ?>" placeholder="Nama produk..." class="w-full p-4 bg-slate-50 rounded-2xl focus:ring-2 focus:ring-blue-500 outline-none transition-all" required>
                        </div>

                        <div class="grid grid-cols-2 gap-3">
                            <div class="space-y-1">
                                <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Price</label>
                                <input type="number" name="price" value="<?php echo $e['price']??''; ?>" class="w-full p-4 bg-slate-50 rounded-2xl focus:ring-2 focus:ring-blue-500 outline-none transition-all" required>
                            </div>
                            <div class="space-y-1">
                                <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Category</label>
                                <select name="cat" class="w-full p-4 bg-slate-50 rounded-2xl outline-none appearance-none cursor-pointer">
                                    <option value="Fashion" <?php if(($e['category']??'')=='Fashion') echo 'selected'; ?>>Fashion</option>
                                    <option value="Lebaran" <?php if(($e['category']??'')=='Lebaran') echo 'selected'; ?>>Lebaran</option>
                                    <option value="Rumah" <?php if(($e['category']??'')=='Rumah') echo 'selected'; ?>>Rumah</option>
                                </select>
                            </div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Thumbnail Image</label>
                            <div class="relative w-full p-4 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200 hover:border-blue-400 transition-colors">
                                <input type="file" name="img_file" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                                <div class="text-center text-xs text-slate-400 font-medium">Click or Drag Image</div>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-3">
                            <div class="space-y-1">
                                <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Affiliate Link</label>
                                <input type="text" name="link" value="<?php echo $e['affiliate_link']??''; ?>" placeholder="https://..." class="w-full p-4 bg-slate-50 rounded-2xl focus:ring-2 focus:ring-blue-500 outline-none transition-all">
                            </div>
                            <div class="space-y-1">
                                <label class="text-[10px] font-bold text-slate-400 ml-2 uppercase">Platform</label>
                                <select name="plat" class="w-full p-4 bg-slate-50 rounded-2xl outline-none">
                                    <option value="Shopee" <?php if(($e['platform']??'')=='Shopee') echo 'selected'; ?>>Shopee</option>
                                    <option value="TikTok" <?php if(($e['platform']??'')=='TikTok') echo 'selected'; ?>>TikTok</option>
                                </select>
                            </div>
                        </div>

                        <button type="submit" name="simpan" class="w-full bg-slate-900 text-white py-5 rounded-[1.8rem] font-black shadow-xl hover:bg-blue-600 transition-all uppercase tracking-tighter text-sm">
                            <?php echo $e ? "Save Changes" : "Publish Product"; ?>
                        </button>
                        <?php if($e): ?>
                            <a href="masukpakadmingas.php" class="block text-center text-[10px] font-black text-slate-400 uppercase tracking-widest pt-2">Cancel Edit</a>
                        <?php endif; ?>
                    </form>
                </section>
            </div>

            <div class="md:col-span-3">
                <div class="flex justify-between items-end mb-6 px-4">
                    <h3 class="text-xl font-black text-slate-800 tracking-tighter italic">PRODUCT <span class="text-blue-600">LIST</span></h3>
                    <form method="get" class="relative">
                        <input type="text" name="q" value="<?php echo $search; ?>" placeholder="Search..." class="bg-white pl-4 pr-10 py-2 rounded-full text-xs border border-slate-100 outline-none focus:ring-2 focus:ring-blue-500 w-32 md:w-48 transition-all">
                        <button type="submit" class="absolute right-3 top-2 text-slate-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                        </button>
                    </form>
                </div>

                <div class="space-y-4">
                    <?php 
                    $sql = "SELECT * FROM fashion_products";
                    if($search) { $sql .= " WHERE title LIKE '%$search%'"; }
                    $sql .= " ORDER BY id DESC";
                    $res = mysqli_query($conn, $sql);
                    while($row = mysqli_fetch_assoc($res)){ 
                    ?>
                    <div class="bg-white p-4 rounded-[2.2rem] flex items-center gap-4 shadow-sm border border-slate-50 hover:shadow-md transition-all">
                        <div class="relative group">
                            <img src="<?php echo $row['image_url']; ?>" class="w-20 h-20 object-cover rounded-[1.5rem] bg-slate-100 group-hover:scale-105 transition-transform duration-300">
                            <div class="absolute -top-1 -right-1 bg-white p-1 rounded-full shadow-sm">
                                <div class="w-3 h-3 rounded-full <?php echo ($row['platform'] == 'Shopee' ? 'bg-orange-500' : 'bg-black'); ?>"></div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <h4 class="text-sm font-bold text-slate-800 truncate leading-tight mb-1"><?php echo $row['title']; ?></h4>
                            <p class="text-blue-600 font-black text-xs">Rp <?php echo number_format($row['price'],0,',','.'); ?></p>
                            <span class="inline-block mt-2 text-[8px] font-black uppercase tracking-widest text-slate-300 bg-slate-50 px-2 py-1 rounded-full"><?php echo $row['category']; ?></span>
                        </div>
                        <div class="flex flex-col gap-2">
                            <a href="?edit=<?php echo $row['id']; ?>" class="p-3 bg-blue-50 text-blue-600 rounded-2xl hover:bg-blue-600 hover:text-white transition-all">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg>
                            </a>
                            <a href="?hapus=<?php echo $row['id']; ?>" class="p-3 bg-red-50 text-red-500 rounded-2xl hover:bg-red-500 hover:text-white transition-all" onclick="return confirm('Hapus produk?')">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                            </a>
                        </div>
                    </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>

    <div class="md:hidden fixed bottom-0 left-0 right-0 bg-white/80 backdrop-blur-lg border-t border-slate-100 p-4 flex justify-around items-center z-50 rounded-t-[2.5rem] shadow-2xl">
        <button onclick="window.scrollTo({top: 0, behavior: 'smooth'})" class="p-3 text-blue-600 bg-blue-50 rounded-2xl">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /></svg>
        </button>
        <a href="index.php" class="p-3 text-slate-400">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>
        </a>
        <a href="?logout=true" class="p-3 text-red-400">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" /></svg>
        </a>
    </div>

</body>
</html>