<?php
session_start();
include_once('../includes/db.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$categories = fetchAll("SELECT * FROM categories");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    function uploadImage($fieldName, $uploadDir) {
        if (isset($_FILES[$fieldName]) && $_FILES[$fieldName]['error'] === 0) {
            $fileName = time() . '_' . basename($_FILES[$fieldName]['name']);
            $targetFile = $uploadDir . $fileName;
            if (move_uploaded_file($_FILES[$fieldName]['tmp_name'], $targetFile)) {
                return 'uploads/product_images/' . $fileName;
            }
        }
        return '';
    }

    $name = sanitize($_POST['name']);
    $description = sanitize($_POST['description']);
    $price = floatval($_POST['price']);
    $discount = floatval($_POST['discount']);
    $is_new = isset($_POST['is_new']) ? 1 : 0;
    $category_id = intval($_POST['category_id']);
    $print_price = floatval($_POST['print_price']);
    $sizes = isset($_POST['sizes']) ? implode(',', $_POST['sizes']) : '';

    $uploadDir = '../uploads/product_images/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $front_image = uploadImage('front_image', $uploadDir);
    $back_image = uploadImage('back_image', $uploadDir);

    $query = "INSERT INTO products 
        (name, description, price, discount, is_new, category_id, sizes, print_price, front_image, back_image)
        VALUES 
        ('$name', '$description', $price, $discount, $is_new, $category_id, '$sizes', $print_price, '$front_image', '$back_image')";

    if (mysqli_query($conn, $query)) {
        $success = "✅ Product added successfully.";
    } else {
        $error = "❌ Error adding product: " . mysqli_error($conn);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Product - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f1f5f9;
        }
        .main-content {
            margin-left: 250px;
            padding: 30px;
        }
        .card {
            border-radius: 16px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        }
        .card-header {
            font-size: 18px;
            font-weight: 600;
            background-color: #000;
            color: #fff;
        }
    </style>
</head>
<body>

<div class="d-flex">
    <?php include('admin_sidebar.php'); ?>

    <div class="main-content flex-grow-1">
        <div class="card">
            <div class="card-header">Add New Product</div>
            <div class="card-body p-4">
                <?php if (isset($success)): ?>
                    <div class="alert alert-success"><?= $success ?></div>
                <?php elseif (isset($error)): ?>
                    <div class="alert alert-danger"><?= $error ?></div>
                <?php endif; ?>

                <form method="post" enctype="multipart/form-data">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Product Name</label>
                            <input name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Category</label>
                            <select name="category_id" class="form-select" required>
                                <option value="" disabled selected>Select Category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-12">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="4"></textarea>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">Price</label>
                            <input name="price" type="number" step="0.01" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Discount (%)</label>
                            <input name="discount" type="number" step="0.1" class="form-control">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_new" id="is_new">
                                <label class="form-check-label" for="is_new">Mark as New</label>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Available Sizes</label><br>
                            <?php
                            $fixedSizes = ['S', 'M', 'L', 'XL', 'XXL', 'XXXL'];
                            foreach ($fixedSizes as $size): ?>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="sizes[]" value="<?= $size ?>" id="size_<?= $size ?>">
                                    <label class="form-check-label" for="size_<?= $size ?>"><?= $size ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Print Price</label>
                            <input name="print_price" type="number" step="0.01" class="form-control">
                        </div>

                        <!-- Images -->
                        <div class="col-md-6">
                            <label class="form-label">Front Image</label>
                            <input type="file" name="front_image" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Back Image</label>
                            <input type="file" name="back_image" class="form-control" required>
                        </div>

                        <div class="col-12 text-end">
                            <button type="submit" class="btn btn-success px-4">Add Product</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
