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

// Only admins
if (!isset($_SESSION['user_id']) || ($_SESSION['is_admin'] ?? 0) != 1) {
    header("Location: login.php");
    exit();
}

// Initialize error array
$errors = [];

// Validate required fields
$name = trim($_POST['name'] ?? '');
if ($name === '') $errors[] = "Product name is required";

$sku = trim($_POST['sku'] ?? '');
if ($sku === '') $errors[] = "SKU is required";

$price = floatval($_POST['price'] ?? 0);
if ($price <= 0) $errors[] = "Price must be greater than 0";

$stock = intval($_POST['stock'] ?? 1);
if ($stock < 1) $errors[] = "Stock must be at least 1";

// Optional fields
$category = $_POST['category'] ?? '';
$gender = $_POST['gender'] ?? '';
$brand = $_POST['brand'] ?? '';
$material = $_POST['material'] ?? '';
$sizes = !empty($_POST['sizes']) ? json_encode(array_map('trim', explode(',', $_POST['sizes']))) : null;
$colors = !empty($_POST['colors']) ? json_encode(array_map('trim', explode(',', $_POST['colors']))) : null;
$description = $_POST['description'] ?? '';

// Handle file uploads
$allImages = [];
$mainImage = null;

if (!empty($_FILES['images']['name'][0])) {
    foreach ($_FILES['images']['name'] as $key => $filename) {
        $tmp = $_FILES['images']['tmp_name'][$key];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $newName = uniqid() . '.' . $ext;

        if (move_uploaded_file($tmp, 'uploads/' . $newName)) {
            $allImages[] = $newName;
        } else {
            $errors[] = "Failed to upload image: $filename";
        }
    }
}

if (count($allImages) > 0) {
    $mainImage = $allImages[0];
    $allImagesJson = json_encode($allImages, JSON_UNESCAPED_SLASHES);
} else {
    $mainImage = null;
    $allImagesJson = null;
}

// If there are errors, store in session and redirect
if (!empty($errors)) {
    $_SESSION['add_errors'] = $errors;
    header("Location: admin-products.php");
    exit();
}

// Insert into DB
try {
    $stmt = $conn->prepare("INSERT INTO products 
        (name, sku, category, gender, brand, price, stock, material, sizes, colors, image, images, description)
        VALUES (:name, :sku, :category, :gender, :brand, :price, :stock, :material, :sizes, :colors, :image, :images, :description)");

    $stmt->execute([
        ':name'=>$name,
        ':sku'=>$sku,
        ':category'=>$category,
        ':gender'=>$gender,
        ':brand'=>$brand,
        ':price'=>$price,
        ':stock'=>$stock,
        ':material'=>$material,
        ':sizes'=>$sizes,
        ':colors'=>$colors,
        ':image'=>$mainImage,
        ':images'=>$allImagesJson,
        ':description'=>$description
    ]);

    header("Location: admin-products.php?added=1");
    exit();

} catch (PDOException $e) {
    $_SESSION['add_errors'] = ["Failed to save product. Please try again."];
    header("Location: admin-products.php");
    exit();
}
