<?php
// Set headers for JSON response and CORS
header('Content-Type: application/json');
require_once '../config/cors.php';

// Include necessary files
require_once '../config/database.php';
require_once '../models/Product.php';
require_once '../middleware/auth.php';

// Initialize database and object
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);

// Get the request method
$method = $_SERVER['REQUEST_METHOD'];
// In your products API endpoint
function searchProducts($searchQuery) {
    $conn = getDBConnection();
    
    // Normalize search query
    $normalizedQuery = trim($searchQuery);
    
    // Remove extra spaces and prepare for LIKE query
    $likeQuery = '%' . str_replace(' ', '%', $normalizedQuery) . '%';
    
    $sql = "SELECT p.*, c.name as category_name, c.slug as category_slug 
            FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            WHERE (
                LOWER(REPLACE(p.name, ' ', '')) LIKE LOWER(REPLACE(?, ' ', '')) OR
                LOWER(p.name) LIKE LOWER(?) OR
                LOWER(p.brand) LIKE LOWER(?) OR
                LOWER(p.description) LIKE LOWER(?) OR
                LOWER(p.sku) LIKE LOWER(?)
            )
            AND p.is_active = 1
            ORDER BY 
                CASE 
                    WHEN LOWER(p.name) = LOWER(?) THEN 1
                    WHEN LOWER(p.name) LIKE LOWER(?) THEN 2
                    WHEN LOWER(REPLACE(p.name, ' ', '')) LIKE LOWER(REPLACE(?, ' ', '')) THEN 3
                    ELSE 4
                END,
                p.name ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sssssssss', 
        $likeQuery, $likeQuery, $likeQuery, $likeQuery, $likeQuery,
        $normalizedQuery, $normalizedQuery, $likeQuery, $likeQuery
    );
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
    
    return $products;
}

switch ($method) {
    case 'GET':
        // --- LOGIC UPDATED TO HANDLE SINGLE PRODUCT, SIMILAR TO CATEGORY API ---

        // Check if an ID or slug is provided for a single product
        if (isset($_GET['id']) || isset($_GET['slug'])) {
            
            // Assign ID or Slug to the product object
            // Note: Your Product model must have a 'getSingleProduct' method that can find a product by its ID or slug.
            if (isset($_GET['id'])) {
                $product->id = $_GET['id'];
            } else {
                $product->slug = $_GET['slug'];
            }
            
            // Attempt to fetch the single product
            if ($product->getSingleProduct()) {
                // If product is found, create an array with its details
                $product_details = [
                    'id' => $product->id,
                    'name' => $product->name,
                    'slug' => $product->slug,
                    'brand' => $product->brand,
                    'description' => $product->description,
                    'base_price' => $product->base_price,
                    'sku' => $product->sku,
                    'stock' => $product->stock,
                    'category_id' => $product->category_id,
                    'category_name' => $product->category_name, // Assuming this is joined in the model
                    'image_url' => $product->image_url, // Assuming this property exists
                    'created_at' => $product->created_at
                ];
                
                http_response_code(200);
                echo json_encode(['success' => true, 'product' => $product_details]);

            } else {
                // If no product is found
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Product not found']);
            }
        } else {
            // --- ORIGINAL LOGIC FOR GETTING ALL PRODUCTS WITH FILTERS ---
            
            // Get query parameters for filtering and pagination
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 12;
            $category = isset($_GET['category']) ? $_GET['category'] : null;
            $brand = isset($_GET['brand']) ? $_GET['brand'] : null;
            $search = isset($_GET['search']) ? $_GET['search'] : null;
            $minPrice = isset($_GET['minPrice']) ? (float)$_GET['minPrice'] : null;
            $maxPrice = isset($_GET['maxPrice']) ? (float)$_GET['maxPrice'] : null;
            $sortBy = isset($_GET['sortBy']) ? $_GET['sortBy'] : 'created_at';
            $sortOrder = isset($_GET['sortOrder']) ? $_GET['sortOrder'] : 'DESC';

            try {
                // Fetch the list of products
                $result = $product->getProducts($page, $limit, $category, $brand, $search, $minPrice, $maxPrice, $sortBy, $sortOrder);

                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'products' => $result['products'],
                    'pagination' => $result['pagination']
                ]);
            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Internal Server Error: ' . $e->getMessage()
                ]);
            }
        }
        break;

    case 'POST':
        // Create new product (Admin only)
        // This part remains unchanged
        $user = requireAdmin();
        $data = json_decode(file_get_contents("php://input"));

        if (!$data || !isset($data->name) || !isset($data->brand) || !isset($data->base_price) || !isset($data->sku) || !isset($data->category_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Missing required fields']);
            break;
        }

        $product->name = $data->name;
        $product->brand = $data->brand;
        $product->description = $data->description ?? '';
        $product->base_price = $data->base_price;
        $product->sku = $data->sku;
        $product->stock = $data->stock ?? 0;
        $product->category_id = $data->category_id;
        // You should also handle the slug, maybe generate it automatically in the model
        $product->slug = $data->slug ?? ''; 


        try {
            $productId = $product->create();
            if ($productId) {
                http_response_code(201);
                echo json_encode(['success' => true, 'message' => 'Product created successfully', 'product_id' => $productId]);
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Failed to create product']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Internal Server Error: ' . $e->getMessage()]);
        }
        break;

    default:
        // This part remains unchanged
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        break;
}