<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_auth(['admin']);

header('Content-Type: application/json');

try {
    $pdo = hw_db();
    
    // Get form data
    $name = $_POST['name'] ?? '';
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $price = isset($_POST['price']) ? (float)$_POST['price'] : 0;
    $stock_quantity = isset($_POST['stock_quantity']) ? (int)$_POST['stock_quantity'] : 0;
    $sku = $_POST['sku'] ?? '';
    $description = $_POST['description'] ?? '';
    $active = isset($_POST['active']) && $_POST['active'] === '1' ? 1 : 0;
    
    // Validate required fields
    if (empty($name)) {
        echo json_encode(['success' => false, 'error' => 'Product name is required']);
        exit;
    }
    
    if (!$category_id) {
        echo json_encode(['success' => false, 'error' => 'Please select a valid category']);
        exit;
    }
    
    if ($price <= 0) {
        echo json_encode(['success' => false, 'error' => 'Price must be greater than 0']);
        exit;
    }
    
    // Handle image upload
    $image_url = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../../uploads/products/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $imageExtension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($imageExtension, $allowedExtensions)) {
            $imageName = uniqid('product_') . '.' . $imageExtension;
            $imagePath = $uploadDir . $imageName;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
                $image_url = '/files/atasteofafricanmarketplace/uploads/products/' . $imageName;
            }
        }
    }
    
    // Generate SKU if not provided
    if (empty($sku)) {
        $sku = strtoupper(substr($name, 0, 3)) . '-' . time();
    }
    
    // Insert product
    $stmt = $pdo->prepare('
        INSERT INTO products (
            category_id, name, description, price, 
            stock_quantity, sku, image_url, active, 
            created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ');
    
    $stmt->execute([
        $category_id,
        $name,
        $description,
        $price,
        $stock_quantity,
        $sku,
        $image_url,
        $active
    ]);
    
    $productId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'Product created successfully',
        'product_id' => $productId
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to create product: ' . $e->getMessage()
    ]);
}
