<?php
include 'includes/header.php';

$message = '';

// Handle Delete Request
if (isset($_GET['delete'])) {
    $deleteId = $_GET['delete'];
    try {
        // Optional: Fetch image to delete file
        $stmt = $pdo->prepare("SELECT image FROM products WHERE id = ?");
        $stmt->execute([$deleteId]);
        $img = $stmt->fetchColumn();
        
        // Delete record
        $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$deleteId]);
        
        $message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        Product deleted successfully.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger">Error deleting product.</div>';
    }
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    $category_id = $_POST['category_id'];
    $price = $_POST['price'];
    $stock = $_POST['stock_quantity'];
    $desc = $_POST['description'];
    
    // Upload Image
    $imagePath = 'no-image.jpg';
    if (!empty($_FILES['image']['name'])) {
        $uploaded = uploadImage($_FILES['image']);
        if ($uploaded) $imagePath = $uploaded;
    }

    $sql = "INSERT INTO products (name, category_id, price, stock_quantity, description, image) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    if ($stmt->execute([$name, $category_id, $price, $stock, $desc, $imagePath])) {
        $message = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        Product <strong>'.htmlspecialchars($name).'</strong> added successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    } else {
        $message = '<div class="alert alert-danger">Error adding product.</div>';
    }
}

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

// Fetch Products for List
$prods = $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 LIMIT 10")->fetchAll();
?>

<!-- Page Heading -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold text-dark mb-1">Product Manager</h2>
        <p class="text-muted mb-0">Add new items and manage inventory.</p>
    </div>
</div>

<?= $message ?>

<form method="POST" enctype="multipart/form-data">
    <div class="row g-4 mb-5">
        <!-- Product Details Column -->
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white py-3 fw-bold border-bottom">
                    <i class="fas fa-plus-circle text-primary me-2"></i> Add New Product
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Product Name <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" required placeholder="">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Category <span class="text-danger">*</span></label>
                            <select name="category_id" class="form-select" required>
                                <option value="">Select</option>
                                <?php foreach($cats as $cat): ?>
                                    <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Price ($) <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text">$</span>
                                <input type="number" step="0.01" name="price" class="form-control" required placeholder="0.00">
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Stock Qty</label>
                            <input type="number" name="stock_quantity" class="form-control" value="0">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold small text-uppercase text-muted">Description</label>
                        <textarea name="description" class="form-control" rows="4" placeholder=""></textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Media Column -->
        <div class="col-lg-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white py-3 fw-bold border-bottom">
                    <i class="fas fa-image text-primary me-2"></i> Media & Actions
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <label class="form-label fw-bold small text-uppercase text-muted">Product Image</label>
                        <input type="file" name="image" class="form-control">
                        <div class="form-text small mt-2">Formats: jpg, png, webp.</div>
                    </div>

                    <hr class="text-muted opacity-25">

                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary fw-bold py-2 shadow-sm">
                            <i class="fas fa-check me-2"></i> Save Product
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- Recent Products Table -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-white py-3 fw-bold border-bottom d-flex justify-content-between align-items-center">
        <span><i class="fas fa-list text-primary me-2"></i> Recently Added</span>
        <span class="badge bg-light text-dark border">Latest 10</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light text-muted small text-uppercase">
                    <tr>
                        <th class="ps-4">Image</th>
                        <th>Product Info</th>
                        <th>Price</th>
                        <th>Stock</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($prods)): ?>
                        <tr><td colspan="5" class="text-center py-4 text-muted">No products found.</td></tr>
                    <?php else: ?>
                        <?php foreach($prods as $p): ?>
                        <tr>
                            <td class="ps-4">
                                <img src="../<?= $p['image'] ?>" width="40" height="40" class="rounded border object-fit-cover">
                            </td>
                            <td>
                                <div class="fw-bold text-dark"><?= htmlspecialchars($p['name']) ?></div>
                                <small class="text-muted"><?= htmlspecialchars($p['category_name'] ?? 'Uncategorized') ?></small>
                            </td>
                            <td class="fw-bold text-dark">$<?= number_format($p['price'], 2) ?></td>
                            <td>
                                <?php if($p['stock_quantity'] > 0): ?>
                                    <span class="badge bg-success-subtle text-success border border-success-subtle"><?= $p['stock_quantity'] ?> in stock</span>
                                <?php else: ?>
                                    <span class="badge bg-danger-subtle text-danger border border-danger-subtle">Out of stock</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end pe-4">
                                <div class="btn-group">
                                    <a href="edit_product.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-outline-warning" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="add_product.php?delete=<?= $p['id'] ?>" 
                                       class="btn btn-sm btn-outline-danger" 
                                       onclick="return confirm('Are you sure you want to delete this product?');" 
                                       title="Delete">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Closing divs matching the opening structure in header.php -->
</div></div></div>
</body>
</html>