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

hw_require_method(['POST']);
hw_require_auth();

try {
    $pdo = hw_db();
    
    // Get form data
    $name = $_POST['name'] ?? '';
    $category_id = (int)($_POST['category_id'] ?? 0);
    $price = (float)($_POST['price'] ?? 0);
    $stock_quantity = (int)($_POST['stock_quantity'] ?? 0);
    $sku = $_POST['sku'] ?? null;
    $description = $_POST['description'] ?? '';
    $active = (int)($_POST['active'] ?? 1);
    
    // Validate required fields
    if (!$name || !$category_id || $price <= 0) {
        hw_json(['success' => false, 'message' => 'Missing required fields'], 400);
        exit;
    }
    
    // Handle image upload
    $image_url = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/../../uploads/products/';
        
        // Create directory if it doesn't exist
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (!in_array(strtolower($file_ext), $allowed_exts)) {
            hw_json(['success' => false, 'message' => 'Invalid image format'], 400);
            exit;
        }
        
        $filename = 'product_' . time() . '_' . uniqid() . '.' . $file_ext;
        $file_path = $upload_dir . $filename;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
            $image_url = '/files/atasteofafricanmarketplace/uploads/products/' . $filename;
        }
    }
    
    // Check if SKU already exists
    if ($sku) {
        $stmt = $pdo->prepare("SELECT id FROM products WHERE sku = ?");
        $stmt->execute([$sku]);
        if ($stmt->fetch()) {
            hw_json(['success' => false, 'message' => 'SKU already exists'], 400);
            exit;
        }
    }
    
    // Insert product
    $stmt = $pdo->prepare("
        INSERT INTO products (
            coach_id, category_id, name, description, 
            price, stock_quantity, sku, image_url, active, 
            created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    
    $coach_id = null; // Admin-created products have no coach initially
    
    $stmt->execute([
        $coach_id,
        $category_id,
        $name,
        $description,
        $price,
        $stock_quantity,
        $sku ?: null,
        $image_url,
        $active
    ]);
    
    $product_id = $pdo->lastInsertId();
    
    hw_json([
        'success' => true,
        'message' => 'Product created successfully',
        'product_id' => $product_id
    ]);
    
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
