<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/Database.php';
require_once __DIR__ . '/../models/Product.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

$product = new Product();

if ($method === 'GET' && $action === 'get_all') {
    $categoryId = isset($_GET['category_id']) ? $_GET['category_id'] : null;
    $products = $product->getAllProducts($categoryId);
    echo json_encode($products);
} else if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $prod = $product->getProduct($id);
    
    if ($prod) {
        echo json_encode($prod);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Product not found']);
    }
} else if ($method === 'GET' && $action === 'by_barcode') {
    $barcode = isset($_GET['barcode']) ? $_GET['barcode'] : '';
    $prod = $product->getProductByBarcode($barcode);
    
    if ($prod) {
        echo json_encode($prod);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Product not found']);
    }
} else if ($method === 'GET' && $action === 'low_stock') {
    $products = $product->getLowStockProducts();
    echo json_encode($products);
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    if ($product->createProduct($data)) {
        echo json_encode(['success' => true, 'message' => 'Product created']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create product']);
    }
} else if ($method === 'PUT' && $action === 'update') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $data = json_decode(file_get_contents("php://input"), true);
    
    if ($product->updateProduct($id, $data)) {
        echo json_encode(['success' => true, 'message' => 'Product updated']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update product']);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
