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

// এডমিন চেক
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: index.php"); exit();
}

$msg = "";
$current_section = $_GET['section'] ?? 'devices';

// --- ১. ইউজার ম্যানেজমেন্ট লজিক ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // ইউজার আপডেট
    if (isset($_POST['update_user_full'])) {
        $uid = $_POST['u_id'];
        $u_name = $conn->real_escape_string($_POST['u_name']);
        $u_bal = $_POST['u_bal'];
        $u_pass = $_POST['u_pass'];
        $conn->query("UPDATE users SET username='$u_name', balance='$u_bal' WHERE id=$uid");
        if (!empty($u_pass)) {
            $hashed_pass = password_hash($u_pass, PASSWORD_DEFAULT);
            $conn->query("UPDATE users SET password='$hashed_pass' WHERE id=$uid");
        }
        $msg = "User Updated!";
    }

    // নতুন ইউজার তৈরি
    if (isset($_POST['add_user'])) {
        $username = $conn->real_escape_string($_POST['username']);
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $balance = $_POST['balance'] ?? 0;
        $conn->query("INSERT INTO users (username, password, balance, role) VALUES ('$username', '$password', '$balance', 'user')");
        $msg = "User Created Successfully!";
    }

    // ব্র্যান্ড সেভ/আপডেট
    if (isset($_POST['save_brand'])) {
        $name = $conn->real_escape_string($_POST['name']);
        $price = $_POST['price'];
        $brand_id = $_POST['brand_id'] ?? null;

        if ($brand_id) {
            $sql = "UPDATE brands SET name='$name', price='$price' WHERE id=$brand_id";
            if (!empty($_FILES["logo"]["name"])) {
                $file_name = "logo_" . time() . "_" . $_FILES["logo"]["name"];
                move_uploaded_file($_FILES["logo"]["tmp_name"], "../uploads/logos/" . $file_name);
                $db_path = "uploads/logos/" . $file_name;
                $sql = "UPDATE brands SET name='$name', price='$price', logo='$db_path' WHERE id=$brand_id";
            }
            $conn->query($sql); $msg = "Brand Updated!";
        } else {
            $file_name = "logo_" . time() . "_" . $_FILES["logo"]["name"];
            move_uploaded_file($_FILES["logo"]["tmp_name"], "../uploads/logos/" . $file_name);
            $db_path = "uploads/logos/" . $file_name;
            $conn->query("INSERT INTO brands (name, logo, price) VALUES ('$name', '$db_path', '$price')");
            $msg = "New Brand Added!";
        }
    }

    // মডেল সেভ/আপডেট (ডুপ্লিকেট চেক সহ)
    if (isset($_POST['save_model'])) {
        $brand_id = $_POST['brand_id'];
        $model_name = $conn->real_escape_string($_POST['model_name']);
        $model_id = $_POST['model_id'] ?? null;

        if (!$model_id) {
            // ডুপ্লিকেট চেক
            $check = $conn->query("SELECT id FROM models WHERE brand_id='$brand_id' AND model_name='$model_name'");
            if($check->num_rows > 0) {
                $msg = "Error: This model already exists for this brand!";
            } else {
                $conn->query("INSERT INTO models (brand_id, model_name) VALUES ('$brand_id', '$model_name')");
                $msg = "Model Added!";
            }
        } else {
            $conn->query("UPDATE models SET brand_id='$brand_id', model_name='$model_name' WHERE id=$model_id");
            $msg = "Model Updated!";
        }
    }
}

// ২. ডিলিট লজিক
if (isset($_GET['del_brand'])) { $conn->query("DELETE FROM brands WHERE id=".$_GET['del_brand']); header("Location: panel.php?section=devices"); }
if (isset($_GET['del_model'])) { $conn->query("DELETE FROM models WHERE id=".$_GET['del_model']); header("Location: panel.php?section=devices"); }
if (isset($_GET['del_user'])) { $conn->query("DELETE FROM users WHERE id=".$_GET['del_user']); header("Location: panel.php?section=users"); }

// ৩. ডাটা ফেচ
$edit_brand_data = (isset($_GET['edit_brand'])) ? $conn->query("SELECT * FROM brands WHERE id=".$_GET['edit_brand'])->fetch_assoc() : null;
$edit_model_data = (isset($_GET['edit_model'])) ? $conn->query("SELECT * FROM models WHERE id=".$_GET['edit_model'])->fetch_assoc() : null;
$edit_user_data = (isset($_GET['edit_user'])) ? $conn->query("SELECT * FROM users WHERE id=".$_GET['edit_user'])->fetch_assoc() : null;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sensi Pro Admin | Master Control</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700&family=Rajdhani:wght@600&display=swap');
        body { background: #020202; color: #fff; font-family: 'Rajdhani', sans-serif; }
        .orbitron { font-family: 'Orbitron', sans-serif; }
        .glass { background: rgba(15, 15, 15, 0.85); backdrop-filter: blur(15px); border: 1px solid rgba(255,255,255,0.05); border-radius: 24px; }
        .input-style { background: #000; border: 1px solid #222; border-radius: 12px; padding: 12px; width: 100%; outline: none; color: #fff; }
        .tab-btn { padding: 10px 20px; font-weight: bold; border-radius: 12px; transition: 0.3s; font-size: 13px; }
        .tab-active { background: #dc2626; color: white; box-shadow: 0 0 15px rgba(220, 38, 38, 0.4); }
    </style>
</head>
<body class="p-4 md:p-8">

    <div class="max-w-7xl mx-auto space-y-8">
        
        <!-- Header -->
        <div class="glass p-6 flex flex-col md:flex-row justify-between items-center gap-6 border-l-4 border-l-red-600">
            <div>
                <h1 class="text-3xl font-black orbitron italic text-white leading-none">ADMIN <span class="text-red-600 uppercase">PRO</span></h1>
                <p class="text-gray-500 text-[10px] tracking-[5px] uppercase mt-1">System Controller</p>
            </div>
            
            <div class="flex gap-3">
                <a href="?section=devices" class="tab-btn <?php echo $current_section == 'devices' ? 'tab-active' : 'bg-white/5 text-gray-500'; ?>"><i class="fas fa-microchip mr-1"></i> Device Manager</a>
                <a href="?section=users" class="tab-btn <?php echo $current_section == 'users' ? 'tab-active' : 'bg-white/5 text-gray-500'; ?>"><i class="fas fa-users mr-1"></i> User Manager</a>
                <a href="logout.php" class="bg-red-600/10 text-red-500 px-5 py-2 rounded-xl border border-red-600/20 font-bold text-xs uppercase italic">Logout</a>
            </div>
        </div>

        <?php if($msg): ?>
            <div class="bg-cyan-500/10 border border-cyan-500/20 text-cyan-400 p-4 rounded-2xl text-center font-bold italic"><?php echo $msg; ?></div>
        <?php endif; ?>

        <!-- --- USER SECTION --- -->
        <?php if($current_section == 'users'): ?>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div class="lg:col-span-1 glass p-6 h-fit">
                    <h2 class="orbitron text-xs text-red-500 mb-6 uppercase tracking-widest italic">User Account Control</h2>
                    <form method="POST" class="space-y-4">
                        <?php if($edit_user_data): ?> <input type="hidden" name="u_id" value="<?php echo $edit_user_data['id']; ?>"> <?php endif; ?>
                        <input type="text" name="<?php echo $edit_user_data ? 'u_name' : 'username'; ?>" value="<?php echo $edit_user_data['username'] ?? ''; ?>" placeholder="Username" class="input-style" required>
                        <input type="text" name="<?php echo $edit_user_data ? 'u_pass' : 'password'; ?>" placeholder="Password (Empty to skip)" class="input-style" <?php echo $edit_user_data ? '' : 'required'; ?>>
                        <input type="number" name="<?php echo $edit_user_data ? 'u_bal' : 'balance'; ?>" value="<?php echo $edit_user_data['balance'] ?? '0'; ?>" placeholder="Balance" class="input-style">
                        <button type="submit" name="<?php echo $edit_user_data ? 'update_user_full' : 'add_user'; ?>" class="w-full bg-red-600 font-black orbitron py-4 rounded-xl text-xs uppercase"><?php echo $edit_user_data ? 'Update' : 'Register'; ?></button>
                    </form>
                </div>
                <div class="lg:col-span-2 glass overflow-hidden">
                    <table class="w-full text-left text-sm italic">
                        <thead class="bg-white/5 uppercase text-gray-500 text-[10px] italic">
                            <tr><th class="p-4">User</th><th>Credits</th><th class="text-right p-4">Actions</th></tr>
                        </thead>
                        <tbody class="divide-y divide-white/5 italic">
                            <?php $users = $conn->query("SELECT * FROM users ORDER BY id DESC"); while($u = $users->fetch_assoc()): ?>
                            <tr class="hover:bg-white/[0.02]">
                                <td class="p-4 font-bold"><?php echo $u['username']; ?></td>
                                <td class="text-green-500 font-bold italic">৳<?php echo $u['balance']; ?></td>
                                <td class="p-4 text-right space-x-2">
                                    <a href="?section=users&edit_user=<?php echo $u['id']; ?>" class="text-yellow-500"><i class="fas fa-edit"></i></a>
                                    <a href="?section=users&del_user=<?php echo $u['id']; ?>" class="text-red-500" onclick="return confirm('Delete?')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <!-- --- DEVICE SECTION --- -->
        <?php elseif($current_section == 'devices'): ?>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <!-- Brand Area -->
                <div class="space-y-6">
                    <div class="glass p-6">
                        <h2 class="orbitron text-xs text-cyan-400 mb-6 uppercase tracking-widest italic"><?php echo $edit_brand_data ? 'Edit Brand' : 'Add Brand'; ?></h2>
                        <form method="POST" enctype="multipart/form-data" class="space-y-4">
                            <?php if($edit_brand_data): ?> <input type="hidden" name="brand_id" value="<?php echo $edit_brand_data['id']; ?>"> <?php endif; ?>
                            <input type="text" name="name" value="<?php echo $edit_brand_data['name'] ?? ''; ?>" placeholder="Brand Name" class="input-style" required>
                            <input type="number" name="price" value="<?php echo $edit_brand_data['price'] ?? ''; ?>" placeholder="Price" class="input-style" required>
                            <input type="file" name="logo" class="input-style text-xs text-gray-500">
                            <button type="submit" name="save_brand" class="w-full bg-cyan-600 font-bold orbitron py-4 rounded-xl text-xs uppercase italic">Save Brand</button>
                        </form>
                    </div>
                    <!-- Brand List Table -->
                    <div class="glass overflow-hidden">
                        <div class="p-4 bg-white/5 border-b border-white/5">
                            <input type="text" id="brandSearch" placeholder="Search Brand..." class="input-style !py-2 text-xs w-full italic">
                        </div>
                        <table class="w-full text-left text-sm" id="brandTable">
                            <tbody class="divide-y divide-white/5 italic">
                                <?php $brands = $conn->query("SELECT * FROM brands ORDER BY id DESC"); while($b = $brands->fetch_assoc()): ?>
                                <tr class="brand-row hover:bg-white/[0.02]">
                                    <td class="p-4 flex items-center gap-3"><img src="../<?php echo $b['logo']; ?>" class="h-8 w-8 object-contain"> <b class="b-name"><?php echo $b['name']; ?></b></td>
                                    <td class="p-4 text-right">
                                        <a href="?edit_brand=<?php echo $b['id']; ?>&section=devices" class="text-yellow-500 mr-2"><i class="fas fa-edit"></i></a>
                                        <a href="?del_brand=<?php echo $b['id']; ?>&section=devices" class="text-red-500"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Model Area -->
                <div class="space-y-6">
                    <div class="glass p-6">
                        <h2 class="orbitron text-xs text-yellow-500 mb-6 uppercase tracking-widest italic"><?php echo $edit_model_data ? 'Edit Model' : 'Add Model'; ?></h2>
                        <form method="POST" class="space-y-4">
                            <?php if($edit_model_data): ?> <input type="hidden" name="model_id" value="<?php echo $edit_model_data['id']; ?>"> <?php endif; ?>
                            <select name="brand_id" class="input-style" required>
                                <option value="">Select Brand</option>
                                <?php $bs = $conn->query("SELECT * FROM brands"); while($b = $bs->fetch_assoc()): ?>
                                <option value="<?php echo $b['id']; ?>" <?php if($edit_model_data && $edit_model_data['brand_id']==$b['id']) echo 'selected'; ?>><?php echo $b['name']; ?></option>
                                <?php endwhile; ?>
                            </select>
                            <input type="text" name="model_name" value="<?php echo $edit_model_data['model_name'] ?? ''; ?>" placeholder="Model Name" class="input-style" required>
                            <button type="submit" name="save_model" class="w-full bg-yellow-600 font-bold orbitron py-4 rounded-xl text-xs uppercase italic">Save Model</button>
                        </form>
                    </div>
                    <!-- Model List & Search -->
                    <div class="glass overflow-hidden">
                       <div class="p-4 bg-white/5 flex gap-2 border-b border-white/5">
                            <input type="text" id="modelSearch" placeholder="Search Model..." class="input-style !py-2 text-xs italic">
                            <select id="brandFilter" class="bg-black border border-white/10 text-[10px] rounded p-1 italic text-gray-500">
                                <option value="all">All Brands</option>
                                <?php $bs = $conn->query("SELECT * FROM brands"); while($b = $bs->fetch_assoc()) echo "<option value='".$b['name']."'>".$b['name']."</option>"; ?>
                            </select>
                       </div>
                       <table class="w-full text-left text-sm" id="modelTable">
                            <tbody class="divide-y divide-white/5 italic">
                                <?php $models = $conn->query("SELECT models.*, brands.name as bname FROM models JOIN brands ON models.brand_id = brands.id ORDER BY id DESC"); 
                                while($m = $models->fetch_assoc()): ?>
                                <tr class="model-row hover:bg-white/[0.02]" data-brand="<?php echo $m['bname']; ?>">
                                    <td class="p-4 text-[10px] text-gray-500 uppercase italic font-bold"><?php echo $m['bname']; ?></td>
                                    <td class="p-4 font-bold m-name italic"><?php echo $m['model_name']; ?></td>
                                    <td class="p-4 text-right">
                                        <a href="?edit_model=<?php echo $m['id']; ?>&section=devices" class="text-yellow-500 mr-2"><i class="fas fa-edit"></i></a>
                                        <a href="?del_model=<?php echo $m['id']; ?>&section=devices" class="text-red-500"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                       </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // ১. ব্র্যান্ড সার্চ লজিক
        document.getElementById('brandSearch')?.addEventListener('input', function(e) {
            const val = e.target.value.toLowerCase();
            document.querySelectorAll('.brand-row').forEach(row => {
                row.style.display = row.querySelector('.b-name').innerText.toLowerCase().includes(val) ? '' : 'none';
            });
        });

        // ২. মডেল সার্চ লজিক
        document.getElementById('modelSearch')?.addEventListener('input', function(e) {
            const val = e.target.value.toLowerCase();
            document.querySelectorAll('.model-row').forEach(row => {
                row.style.display = row.querySelector('.m-name').innerText.toLowerCase().includes(val) ? '' : 'none';
            });
        });

        // ৩. ব্র্যান্ড অনুযায়ী মডেল ফিল্টার লজিক
        document.getElementById('brandFilter')?.addEventListener('change', function(e) {
            const brand = e.target.value;
            document.querySelectorAll('.model-row').forEach(row => {
                row.style.display = (brand === 'all' || row.getAttribute('data-brand') === brand) ? '' : 'none';
            });
        });
    </script>

</body>
</html>