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

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

// Check if form submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $sku = trim($_POST['sku'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $brand = trim($_POST['brand'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $stock = intval($_POST['stock'] ?? 1);
    $material = trim($_POST['material'] ?? '');
    $sizes = trim($_POST['sizes'] ?? '');
    $description = trim($_POST['description'] ?? '');
    
    // Convert sizes to JSON
    $sizesJson = $sizes ? json_encode(array_map('trim', explode(',', $sizes))) : null;

    // Handle attributes if any
    $attrNames = $_POST['attr_name'] ?? [];
    $attrValues = $_POST['attr_value'] ?? [];
    $attributes = [];
    for ($i = 0; $i < count($attrNames); $i++) {
        $n = trim($attrNames[$i]);
        $v = trim($attrValues[$i]);
        if ($n !== '' && $v !== '') {
            $attributes[$n] = $v;
        }
    }
    $attrJson = $attributes ? json_encode($attributes) : null;

    // Handle image uploads
    $imageNames = [];
    if (!empty($_FILES['images']['name'][0])) {
        $uploadDir = 'uploads/';
        foreach ($_FILES['images']['name'] as $key => $filename) {
            $tmpName = $_FILES['images']['tmp_name'][$key];
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            $newName = uniqid('prod_', true) . '.' . $ext;
            if (move_uploaded_file($tmpName, $uploadDir . $newName)) {
                $imageNames[] = $newName;
            }
        }
        // Save as comma-separated string
        $imagesStr = implode(',', $imageNames);
    } else {
        // Keep existing image
        $stmt = $conn->prepare("SELECT image FROM products WHERE id=?");
        $stmt->execute([$id]);
        $imagesStr = $stmt->fetchColumn();
    }

    // Update database
    $stmt = $conn->prepare("UPDATE products SET 
        name=?, sku=?, category=?, gender=?, brand=?, price=?, stock=?, material=?, sizes=?, attributes=?, image=?, description=?
        WHERE id=?");

    $stmt->execute([
        $name, $sku, $category, $gender, $brand, $price, $stock, $material, $sizesJson, $attrJson, $imagesStr, $description, $id
    ]);

    // Redirect back to admin products page with toast
    header("Location: admin-products.php?updated=1");
    exit();
}

// If someone accesses directly, redirect
header("Location: admin-products.php");
exit();
