<?php
require_once '../config/database.php';

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

try {
    // Validate required fields
    $requiredFields = ['product_name', 'product_brand', 'product_category'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            throw new Exception("$field is required");
        }
    }

    // Handle image upload if provided
    $imagePath = '';
    if (isset($_FILES['product_image']) && $_FILES['product_image']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../uploads/requests/';
        
        // Create directory if it doesn't exist
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $fileName = uniqid() . '_' . basename($_FILES['product_image']['name']);
        $targetPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['product_image']['tmp_name'], $targetPath)) {
            $imagePath = $fileName;  // Store relative path for database
        } else {
            throw new Exception('Failed to upload image');
        }
    } elseif (!empty($_POST['product_image_url'])) {
        $imagePath = $_POST['product_image_url'];
    }

    // Insert request into database
    $stmt = $pdo->prepare("INSERT INTO {$tables['product_requests']} (
        product_name,
        product_brand,
        product_category,
        sub_category,
        barcode,
        product_image_url,
        more_info
    ) VALUES (
        :product_name,
        :product_brand,
        :product_category,
        :sub_category,
        :barcode,
        :product_image_url,
        :more_info
    )");

    $stmt->execute([
        ':product_name' => $_POST['product_name'],
        ':product_brand' => $_POST['product_brand'],
        ':product_category' => $_POST['product_category'],
        ':sub_category' => $_POST['sub_category'] ?? null,
        ':barcode' => $_POST['barcode'] ?? null,
        ':product_image_url' => $imagePath,
        ':more_info' => $_POST['more_info'] ?? null
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'Product request submitted successfully'
    ]);

} catch (Exception $e) {
    error_log("Product request error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?> 