<?php
require_once 'config.php';

// Access Control
if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$message = '';
$error = '';

// Handle Delete Action
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    try {
        $stmt_delete = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt_delete->execute([$delete_id]);
        $message = "Outfit deleted successfully.";
    } catch (PDOException $e) {
        $error = "Failed to delete item: Some orders contain this product.";
    }
}

// Handle Add / Edit form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_product'])) {
    $id = $_POST['product_id'] ?? '';
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $price = floatval($_POST['price']);
    $stock = intval($_POST['stock']);
    $image_url = trim($_POST['image_url']);
    $category_id = intval($_POST['category_id']);

    if (empty($name) || empty($price) || $stock < 0) {
        $error = "Please fill in all required fields correctly.";
    } else {
        if (!empty($id)) {
            // Update
            $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, image_url = ?, category_id = ? WHERE id = ?");
            $stmt->execute([$name, $description, $price, $stock, $image_url, $category_id, $id]);
            $message = "Outfit updated successfully.";
        } else {
            // Insert
            $stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, image_url, category_id) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $description, $price, $stock, $image_url, $category_id]);
            $message = "Outfit added successfully.";
        }
    }
}

// Fetch edit product details if requested
$edit_product = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt_edit = $pdo->prepare("SELECT * FROM products WHERE id = ?");
    $stmt_edit->execute([$edit_id]);
    $edit_product = $stmt_edit->fetch();
}

// Fetch categories for dropdown
$categories = $pdo->query("SELECT * FROM categories")->fetchAll();

// Fetch all products
$products = $pdo->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC")->fetchAll();
?>
<?php include 'header.php'; ?>

<div class="admin-container">
    <aside class="sidebar">
        <ul class="sidebar-menu">
            <li>
                <a href="admin_dashboard.php" class="sidebar-link">📊 Dashboard Overview</a>
            </li>
            <li>
                <a href="admin_products.php" class="sidebar-link active">👗 Manage Clothes</a>
            </li>
            <li>
                <a href="admin_orders.php" class="sidebar-link">📦 Manage Orders</a>
            </li>
            <li>
                <a href="index.php" class="sidebar-link" style="margin-top: 30px; border-top: 1px solid var(--gray-border); padding-top: 20px;">🌐 Go to Shop</a>
            </li>
        </ul>
    </aside>

    <main class="admin-main">
        <div class="section-title">
            <span>Manage Store Clothes</span>
        </div>

        <?php if (!empty($message)): ?>
            <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>

        <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 30px; align-items: start;">
            <!-- Form Card -->
            <div class="table-container">
                <h3 style="font-weight: 700; margin-bottom: 20px;"><?php echo $edit_product ? 'Edit Outfit' : 'Add New Outfit'; ?></h3>
                
                <form action="admin_products.php" method="POST">
                    <input type="hidden" name="product_id" value="<?php echo $edit_product['id'] ?? ''; ?>">
                    
                    <div class="form-group">
                        <label for="name">Outfit Name *</label>
                        <input type="text" id="name" name="name" class="form-control" value="<?php echo htmlspecialchars($edit_product['name'] ?? ''); ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="category_id">Category *</label>
                        <select id="category_id" name="category_id" class="form-control" required>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>" <?php echo (isset($edit_product['category_id']) && $edit_product['category_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label for="price">Price (THB) *</label>
                            <input type="number" id="price" name="price" step="0.01" class="form-control" value="<?php echo $edit_product['price'] ?? ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="stock">Stock *</label>
                            <input type="number" id="stock" name="stock" class="form-control" value="<?php echo $edit_product['stock'] ?? ''; ?>" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="image_url">Image URL</label>
                        <input type="url" id="image_url" name="image_url" class="form-control" placeholder="https://unsplash.com/..." value="<?php echo htmlspecialchars($edit_product['image_url'] ?? ''); ?>">
                    </div>

                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea id="description" name="description" class="form-control" rows="4"><?php echo htmlspecialchars($edit_product['description'] ?? ''); ?></textarea>
                    </div>

                    <button type="submit" name="save_product" class="btn btn-primary" style="width: 100%; margin-top: 10px;">Save Outfit</button>
                    <?php if ($edit_product): ?>
                        <a href="admin_products.php" class="btn btn-outline" style="width: 100%; margin-top: 10px; display: block; text-align: center;">Cancel Edit</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- List Card -->
            <div class="table-container">
                <h3 style="font-weight: 700; margin-bottom: 20px;">Outfit Listing</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Image</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Price</th>
                            <th>Stock</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $prod): ?>
                            <tr>
                                <td>
                                    <img src="<?php echo htmlspecialchars($prod['image_url']); ?>" alt="" style="width: 40px; height: 50px; object-fit: cover; border-radius: var(--radius-sm);">
                                </td>
                                <td><strong><?php echo htmlspecialchars($prod['name']); ?></strong></td>
                                <td><?php echo htmlspecialchars($prod['category_name'] ?? 'General'); ?></td>
                                <td>฿<?php echo number_format($prod['price'], 2); ?></td>
                                <td><?php echo $prod['stock']; ?></td>
                                <td>
                                    <div style="display: flex; gap: 8px;">
                                        <a href="admin_products.php?edit=<?php echo $prod['id']; ?>" class="btn btn-outline" style="padding: 5px 10px; font-size: 11px;">Edit</a>
                                        <a href="admin_products.php?delete=<?php echo $prod['id']; ?>" class="btn btn-primary" style="padding: 5px 10px; font-size: 11px; background: var(--danger);" onclick="return confirm('Are you sure you want to delete this outfit?');">Delete</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

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