<?php
session_start();
require_once 'db_config.php';

// লগইন চেক
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("location: login.php");
    exit;
}

// --- ল্যাঙ্গুয়েজ সেটআপ (Session থেকে) ---
$lang = isset($_SESSION['admin_lang']) ? $_SESSION['admin_lang'] : 'bn';

$words = [
    'bn' => [
        'page_title' => 'ডেমো ম্যানেজ - অ্যাডমিন প্যানেল',
        'top_header' => 'ডেমো ম্যানেজমেন্ট',
        'update_info' => 'ডেমো তথ্য আপডেট করুন',
        'add_new' => '+ নতুন ডেমো ওয়েবসাইট যোগ করুন',
        'demo_name' => 'ডেমোর নাম',
        'category' => 'ক্যাটাগরি',
        'url' => 'ডেমো লিংক (URL)',
        'image' => 'ডেমো ছবি',
        'img_note' => '(পরিবর্তন করতে চাইলে নতুন ছবি দিন)',
        'save' => 'সেভ করুন',
        'update' => 'আপডেট করুন',
        'cancel' => 'ক্যান্সেল',
        'th_img' => 'ছবি',
        'th_name' => 'নাম ও ক্যাটাগরি',
        'th_link' => 'লিংক',
        'th_status' => 'স্ট্যাটাস',
        'th_action' => 'অ্যাকশন',
        'visit' => 'ভিজিট',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'no_img' => 'ছবি নেই',
        'no_data' => 'কোনো ডেমো নেই',
        'msg_add' => 'নতুন ডেমো যুক্ত হয়েছে!',
        'msg_update' => 'ডেমো আপডেট হয়েছে!',
        'msg_delete' => 'ডেমো ডিলিট হয়েছে!',
        'confirm_delete' => 'ডিলিট করবেন?'
    ],
    'en' => [
        'page_title' => 'Demo Manage - Admin Panel',
        'top_header' => 'Demo Management',
        'update_info' => 'Update Demo Information',
        'add_new' => '+ Add New Demo Website',
        'demo_name' => 'Demo Name',
        'category' => 'Category',
        'url' => 'Demo Link (URL)',
        'image' => 'Demo Image',
        'img_note' => '(Upload new to change)',
        'save' => 'Save Now',
        'update' => 'Update Now',
        'cancel' => 'Cancel',
        'th_img' => 'Image',
        'th_name' => 'Name & Category',
        'th_link' => 'Link',
        'th_status' => 'Status',
        'th_action' => 'Action',
        'visit' => 'Visit',
        'active' => 'Active',
        'hidden' => 'Hidden',
        'no_img' => 'No Image',
        'no_data' => 'No demo found',
        'msg_add' => 'New demo added successfully!',
        'msg_update' => 'Demo updated successfully!',
        'msg_delete' => 'Demo deleted successfully!',
        'confirm_delete' => 'Are you sure to delete?'
    ]
];
$t = $words[$lang];

// ================= PHP লজিক শুরু ================= //

// ১. ডেমো সেভ বা আপডেট
if (isset($_POST['save_demo'])) {
    $id = $_POST['demo_id'];
    $name = mysqli_real_escape_string($conn, $_POST['demo_name']);
    $category = mysqli_real_escape_string($conn, $_POST['demo_category']);
    $url = mysqli_real_escape_string($conn, $_POST['demo_url']);

    $image_query = "";
    if (!empty($_FILES['demo_image']['name'])) {
        $image = $_FILES['demo_image']['name'];
        $upload_dir = __DIR__ . "/uploads/";
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $target = $upload_dir . basename($image);
        
        if (move_uploaded_file($_FILES['demo_image']['tmp_name'], $target)) {
            $image_query = ", image='$image'";
        }
    }

    if ($id) {
        $sql = "UPDATE demos SET name='$name', category='$category', url='$url' $image_query WHERE id=$id";
        $msg = $t['msg_update'];
    } else {
        $img_name = !empty($_FILES['demo_image']['name']) ? $_FILES['demo_image']['name'] : '';
        $sql = "INSERT INTO demos (name, category, url, image, status) VALUES ('$name', '$category', '$url', '$img_name', 1)";
        $msg = $t['msg_add'];
    }
    
    if(mysqli_query($conn, $sql)){
        echo "<script>alert('$msg'); window.location.href='demo_manage.php';</script>";
    } else {
        echo "<script>alert('Error: " . mysqli_error($conn) . "');</script>";
    }
}

// ২. স্ট্যাটাস টগল
if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    mysqli_query($conn, "UPDATE demos SET status = 1 - status WHERE id=$id");
    echo "<script>window.location.href='demo_manage.php';</script>";
}

// ৩. ডেমো ডিলিট
if (isset($_GET['delete_demo'])) {
    $id = intval($_GET['delete_demo']);
    $res = mysqli_query($conn, "SELECT image FROM demos WHERE id=$id");
    $row = mysqli_fetch_assoc($res);
    if($row && !empty($row['image'])) {
        $path = __DIR__ . "/uploads/" . $row['image'];
        if (file_exists($path)) { unlink($path); }
    }
    mysqli_query($conn, "DELETE FROM demos WHERE id=$id");
    echo "<script>alert('".$t['msg_delete']."'); window.location.href='demo_manage.php';</script>";
}

// ৪. এডিট ডাটা ফেচ
$edit_data = null;
if (isset($_GET['edit_demo'])) {
    $id = intval($_GET['edit_demo']);
    $res = mysqli_query($conn, "SELECT * FROM demos WHERE id=$id");
    $edit_data = mysqli_fetch_assoc($res);
}
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $t['page_title']; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --accent: #3498db; --bg: #f4f6f9; }
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Segoe UI', sans-serif; }
        body { background: var(--bg); display:flex; min-height:100vh; }
        
        .main-content { margin-left:250px; width:calc(100% - 250px); transition: 0.3s; min-height: 100vh; }
        .content-body { padding: 30px; }

        /* ব্যাজ ও বাটন */
        .status-badge { padding: 5px 10px; border-radius: 20px; font-size: 0.8rem; color: #fff; font-weight: bold; }
        .status-active { background: #27ae60; }
        .status-inactive { background: #e74c3c; }

        .action-btn { padding: 6px 10px; border-radius: 4px; color: #fff; text-decoration: none; font-size: 0.85rem; margin-right: 5px; display: inline-block; }
        .btn-edit { background: #f39c12; }
        .btn-hide { background: #34495e; }
        .btn-show { background: #27ae60; }
        .btn-delete { background: #c0392b; }

        /* ফর্ম */
        .form-container { background: #fff; padding: 25px; border-radius: 8px; margin-bottom: 30px; border-left: 5px solid var(--accent); box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
        .submit-btn { background: var(--accent); color: #fff; padding: 10px 25px; border: none; cursor: pointer; border-radius: 4px; font-size: 1rem; }

        /* টেবিল */
        table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        th, td { padding: 15px; border-bottom: 1px solid #eee; text-align: left; vertical-align: middle; }
        th { background: #f8f9fa; color: var(--primary); }

        @media(max-width:768px){ .main-content{margin-left:0; width:100%;} }
    </style>
</head>
<body>

    <?php include 'sidebar.php'; ?>

    <main class="main-content">
        <!-- গ্লোবাল হেডার ইনক্লুড -->
        <?php include 'top_header.php'; ?>

        <div class="content-body">
            <!-- অ্যাড / এডিট ফর্ম -->
            <div class="form-container">
                <h4><?php echo $edit_data ? $t['update_info'] : $t['add_new']; ?></h4>
                <br>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="demo_id" value="<?php echo $edit_data['id'] ?? ''; ?>">

                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div style="flex: 1; min-width: 250px;">
                            <div class="form-group">
                                <label><?php echo $t['demo_name']; ?></label>
                                <input type="text" name="demo_name" class="form-control" value="<?php echo $edit_data['name'] ?? ''; ?>" required>
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['category']; ?></label>
                                <input type="text" name="demo_category" class="form-control" value="<?php echo $edit_data['category'] ?? ''; ?>">
                            </div>
                        </div>
                        <div style="flex: 1; min-width: 250px;">
                            <div class="form-group">
                                <label><?php echo $t['url']; ?></label>
                                <input type="text" name="demo_url" class="form-control" value="<?php echo $edit_data['url'] ?? ''; ?>" required>
                            </div>
                            <div class="form-group">
                                <label><?php echo $t['image']; ?> <?php echo $edit_data ? $t['img_note'] : ''; ?></label>
                                <input type="file" name="demo_image" class="form-control" <?php echo $edit_data ? '' : 'required'; ?>>
                                <?php if($edit_data && $edit_data['image']): ?>
                                    <img src="uploads/<?php echo $edit_data['image']; ?>" width="60" style="margin-top:5px; border-radius:5px;">
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" name="save_demo" class="submit-btn">
                        <?php echo $edit_data ? $t['update'] : $t['save']; ?>
                    </button>

                    <?php if($edit_data): ?>
                        <a href="demo_manage.php" style="margin-left:10px; color:red; text-decoration:none;"><?php echo $t['cancel']; ?></a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- ডেমো লিস্ট টেবিল -->
            <div style="overflow-x:auto;">
                <table>
                    <thead>
                        <tr>
                            <th><?php echo $t['th_img']; ?></th>
                            <th><?php echo $t['th_name']; ?></th>
                            <th><?php echo $t['th_link']; ?></th>
                            <th><?php echo $t['th_status']; ?></th>
                            <th><?php echo $t['th_action']; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $res = mysqli_query($conn, "SELECT * FROM demos ORDER BY id DESC");
                        if(mysqli_num_rows($res) > 0) {
                            while($row = mysqli_fetch_assoc($res)){
                                $status_text = ($row['status'] == 1) ? $t['active'] : $t['hidden'];
                                $status_class = ($row['status'] == 1) ? 'status-active' : 'status-inactive';
                        ?>
                            <tr>
                                <td>
                                    <?php if($row['image']): ?>
                                        <img src="uploads/<?php echo $row['image']; ?>" width="60" height="40" style="object-fit: cover; border-radius: 5px;">
                                    <?php else: ?>
                                        <span style="color:red; font-size:0.8rem;"><?php echo $t['no_img']; ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <b><?php echo htmlspecialchars($row['name']); ?></b><br>
                                    <span style="background:#eee; padding:2px 6px; border-radius:10px; font-size:0.8rem;"><?php echo htmlspecialchars($row['category']); ?></span>
                                </td>
                                <td><a href="<?php echo htmlspecialchars($row['url']); ?>" target="_blank" style="color:#3498db; text-decoration:none;"><i class="fas fa-external-link-alt"></i> <?php echo $t['visit']; ?></a></td>
                                <td><span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></td>
                                <td>
                                    <a href="demo_manage.php?edit_demo=<?php echo $row['id']; ?>" class="action-btn btn-edit"><i class="fas fa-edit"></i></a>
                                    <a href="demo_manage.php?toggle_status=<?php echo $row['id']; ?>" class="action-btn <?php echo ($row['status'] == 1) ? 'btn-hide' : 'btn-show'; ?>">
                                        <?php if($row['status'] == 1): ?><i class="fas fa-eye-slash"></i><?php else: ?><i class="fas fa-eye"></i><?php endif; ?>
                                    </a>
                                    <a href="demo_manage.php?delete_demo=<?php echo $row['id']; ?>" class="action-btn btn-delete" onclick="return confirm('<?php echo $t['confirm_delete']; ?>')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php } } else { ?>
                            <tr><td colspan="5" style="text-align:center; padding:20px;"><?php echo $t['no_data']; ?></td></tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</body>
</html>