

<?php
require 'auth_check.php';
require '../config/db.php';

// --- LOGIC: HANDLE ACTIONS ---

$vendors_list = $pdo->query("SELECT * FROM vendors WHERE is_active=1")->fetchAll();

// 1. Delete Product
if (isset($_GET['delete_id'])) {
    $pid = $_GET['delete_id'];
    // Delete product (Cascade will delete variants automatically if DB is set up right, but let's be safe)
    $pdo->prepare("DELETE FROM product_variants WHERE product_id = ?")->execute([$pid]);
    $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$pid]);
    header("Location: products.php?msg=deleted");
    exit();
}

// 2. Delete Variant
if (isset($_GET['delete_variant'])) {
    $vid = $_GET['delete_variant'];
    $pid = $_GET['return_id']; // Return to the edit page
    $pdo->prepare("DELETE FROM product_variants WHERE id = ?")->execute([$vid]);
    header("Location: products.php?edit_id=" . $pid . "&msg=variant_deleted");
    exit();
}

// 3. Save Product (Add or Update)
if (isset($_POST['save_product'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(str_replace(' ', '-', $name)); 
    $desc = $_POST['description'];
    $img = $_POST['thumbnail_url'];
    $cat = $_POST['category_id'];
    $status = isset($_POST['is_active']) ? 1 : 0;

    if (!empty($_POST['product_id'])) {
        // UPDATE
        $id = $_POST['product_id'];
        $stmt = $pdo->prepare("UPDATE products SET name=?, slug=?, description=?, thumbnail_url=?, category_id=?, is_active=? WHERE id=?");
        $stmt->execute([$name, $slug, $desc, $img, $cat, $status, $id]);
    } else {
        // INSERT
        $stmt = $pdo->prepare("INSERT INTO products (name, slug, description, thumbnail_url, category_id, is_active) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $slug, $desc, $img, $cat, $status]);
        $id = $pdo->lastInsertId();
    }
    // Redirect to Edit page to add variants
    header("Location: products.php?edit_id=" . $id . "&msg=saved");
    exit();
}

// 4. Add Variant
if (isset($_POST['add_variant'])) {
    $pid = $_POST['product_id'];
    $v_name = $_POST['v_name'];
    $v_price = $_POST['v_price'];
    $v_stock = $_POST['v_stock']; // -1 for unlimited
    
    $stmt = $pdo->prepare("INSERT INTO product_variants (product_id, name, price, stock_qty) VALUES (?, ?, ?, ?)");
    $stmt->execute([$pid, $v_name, $v_price, $v_stock]);
    
    header("Location: products.php?edit_id=" . $pid . "&msg=variant_added");
    exit();
}

// --- FETCH DATA ---

$product_to_edit = null;
$variants = [];

// If Editing, Fetch Product Data
if (isset($_GET['edit_id'])) {
    $edit_id = $_GET['edit_id'];
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$edit_id]);
    $product_to_edit = $stmt->fetch();

    // Fetch Variants for this product
    $vStmt = $pdo->prepare("SELECT * FROM product_variants WHERE product_id = ? ORDER BY price ASC");
    $vStmt->execute([$edit_id]);
    $variants = $vStmt->fetchAll();
}

// Fetch Categories for Dropdown
$categories = $pdo->query("SELECT * FROM categories")->fetchAll();

// Fetch All Products for List
$all_products = $pdo->query("
    SELECT p.*, c.name as cat_name 
    FROM products p 
    LEFT JOIN categories c ON p.category_id = c.id 
    ORDER BY p.id DESC
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Products</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* Helper Styles */
        .btn { padding: 8px 15px; border:none; border-radius:4px; cursor:pointer; color:white; text-decoration:none; font-size:13px; }
        .btn-primary { background:#3498db; }
        .btn-danger { background:#e74c3c; }
        .btn-success { background:#2ecc71; }
        .btn-secondary { background:#95a5a6; }
        
        .form-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; }
        .input-group { margin-bottom: 15px; }
        .input-group label { display:block; font-weight:bold; margin-bottom:5px; font-size:12px; color:#555; }
        .form-control { width:100%; padding:10px; border:1px solid #ddd; border-radius:4px; box-sizing:border-box; }
        
        .variant-box { background:#f9f9f9; padding:20px; border:1px dashed #ccc; border-radius:8px; margin-top:20px; }
        
        /* Toggle Switch */
        .status-active { color: green; font-weight: bold; }
        .status-inactive { color: red; font-weight: bold; }
    </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

    <div class="content">
        
        <?php if(isset($_GET['msg'])): ?>
            <div style="background:#d4edda; color:#155724; padding:10px; margin-bottom:20px; border-radius:5px;">
                Action Completed Successfully.
            </div>
        <?php endif; ?>

        <div style="background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-bottom: 40px;">
            <h2 style="margin-top:0; border-bottom:1px solid #eee; padding-bottom:10px;">
                <?php echo $product_to_edit ? 'Edit Product: ' . htmlspecialchars($product_to_edit['name']) : 'Add New Product'; ?>
            </h2>
            
            <form method="POST">
                <input type="hidden" name="product_id" value="<?php echo $product_to_edit['id'] ?? ''; ?>">
                
                <div class="form-grid">
                    <div>
                        <div class="input-group">
                            <label>Product Name</label>
                            <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($product_to_edit['name'] ?? ''); ?>">
                        </div>
                        
                        <div class="input-group">
                            <label>Description (HTML Allowed)</label>
                            <textarea name="description" rows="8" class="form-control"><?php echo htmlspecialchars($product_to_edit['description'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div>
                        <div class="input-group">
                            <label>Category</label>
                            <select name="category_id" class="form-control">
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo ($product_to_edit && $product_to_edit['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="input-group">
                            <label>Image URL</label>
                            <input type="text" name="thumbnail_url" class="form-control" placeholder="https://..." value="<?php echo htmlspecialchars($product_to_edit['thumbnail_url'] ?? ''); ?>">
                            <?php if($product_to_edit && $product_to_edit['thumbnail_url']): ?>
                                <img src="<?php echo $product_to_edit['thumbnail_url']; ?>" style="width:50px; height:50px; margin-top:5px; object-fit:cover; border-radius:4px;">
                            <?php endif; ?>
                        </div>

                        <div class="input-group">
                            <label>Status</label>
                            <label style="cursor:pointer;">
                                <input type="checkbox" name="is_active" <?php echo (!$product_to_edit || $product_to_edit['is_active']) ? 'checked' : ''; ?>>
                                Visible in Store
                            </label>
                        </div>

                        <button type="submit" name="save_product" class="btn btn-primary" style="width:100%; padding:12px;">
                            <?php echo $product_to_edit ? 'Update Details' : 'Save & Continue'; ?>
                        </button>
                        
                        <?php if($product_to_edit): ?>
                            <a href="products.php" class="btn btn-secondary" style="display:block; text-align:center; margin-top:10px;">Cancel Edit</a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>

        <?php if ($product_to_edit): ?>
        <div class="variant-box">
            <h3 style="margin-top:0;"><i class="fas fa-tags"></i> Pricing Options (Variants)</h3>
            
            <table style="width:100%; background:white; margin-bottom:20px;">
                <thead>
                    <tr style="background:#eee;">
                        <th style="padding:10px;">Plan Name</th>
                        <th>Price (₹)</th>
                        <th>Stock</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($variants) > 0): ?>
                        <?php foreach ($variants as $var): ?>
                        <tr>
                            <td style="padding:10px; border-bottom:1px solid #eee;"><?php echo htmlspecialchars($var['name']); ?></td>
                            <td style="border-bottom:1px solid #eee;">₹<?php echo number_format($var['price']); ?></td>
                            <td style="border-bottom:1px solid #eee;"><?php echo $var['stock_qty'] == -1 ? 'Unlimited' : $var['stock_qty']; ?></td>
                            <td style="border-bottom:1px solid #eee;">
                                <a href="products.php?delete_variant=<?php echo $var['id']; ?>&return_id=<?php echo $product_to_edit['id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this pricing option?')">Delete</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" style="padding:15px; text-align:center; color:#777;">No variants added. This product won't be buyable yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <form method="POST" style="display: flex; gap: 10px; align-items: flex-end; background:#e8f4fd; padding:15px; border-radius:5px;">
                <input type="hidden" name="product_id" value="<?php echo $product_to_edit['id']; ?>">
                
                <div style="flex: 2;">
                    <label style="font-size:12px; font-weight:bold;">Plan Name (e.g. 1 Month)</label>
                    <input type="text" name="v_name" class="form-control" required>
                </div>
                <div style="flex: 1;">
                    <label style="font-size:12px; font-weight:bold;">Price (₹)</label>
                    <input type="number" name="v_price" class="form-control" required>
                </div>
                <div style="flex: 1;">
                    <label style="font-size:12px; font-weight:bold;">Stock (-1 = Unltd)</label>
                    <input type="number" name="v_stock" value="-1" class="form-control" required>
                </div>
                <div>
                    <button type="submit" name="add_variant" class="btn btn-success">Add Option</button>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <h3 style="margin-top:40px; border-bottom:2px solid #3498db; padding-bottom:10px;">Product Inventory</h3>
        <table style="background:white; width:100%;">
            <thead>
                <tr style="background:#f1f1f1;">
                    <th style="padding:10px;">ID</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_products as $p): ?>
                <tr style="border-bottom:1px solid #eee;">
                    <td style="padding:10px;">#<?php echo $p['id']; ?></td>
                    <td>
                        <img src="<?php echo $p['thumbnail_url'] ?: 'https://via.placeholder.com/40'; ?>" style="width: 40px; height: 40px; border-radius: 4px; object-fit: cover;">
                    </td>
                    <td><strong><?php echo htmlspecialchars($p['name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($p['cat_name'] ?? 'Uncategorized'); ?></td>
                    <td>
                        <?php echo $p['is_active'] ? '<span class="status-active">Active</span>' : '<span class="status-inactive">Hidden</span>'; ?>
                    </td>
                    <td>
                        <a href="products.php?edit_id=<?php echo $p['id']; ?>" class="btn btn-primary">Edit</a>
                        <a href="products.php?delete_id=<?php echo $p['id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this product completely?')">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    </div>

</body>
</html>