<?php
/**
 * Products API Endpoint
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Product.php';
require_once __DIR__ . '/../includes/User.php';
require_once __DIR__ . '/../includes/B2B.php';

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

$auth = new Auth();
$product = new Product();
$user = new User();
$b2b = new B2B();
$method = $_SERVER['REQUEST_METHOD'];

$userId = $auth->getUserId();

try {
    switch ($method) {
        case 'GET':
            $id = $_GET['id'] ?? null;
            $slug = $_GET['slug'] ?? null;
            $action = $_GET['action'] ?? '';

            if ($id) {
                // Get product by ID
                $productData = $product->getProductById($id);
                if ($productData) {
                    $productData['price'] = $b2b->calculateProductPrice($productData, $userId);
                    echo json_encode(['success' => true, 'product' => $productData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Product not found']);
                }
            } elseif ($slug) {
                // Get product by slug
                $productData = $product->getProductBySlug($slug);
                if ($productData) {
                    $productData['price'] = $b2b->calculateProductPrice($productData, $userId);
                    echo json_encode(['success' => true, 'product' => $productData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Product not found']);
                }
            } elseif ($action === 'featured') {
                // Get featured products
                $limit = $_GET['limit'] ?? 8;
                $products = $product->getFeaturedProducts($limit);
                foreach ($products as &$p) {
                    $p['price'] = $b2b->calculateProductPrice($p, $userId);
                }
                echo json_encode(['success' => true, 'products' => $products]);
            } elseif ($action === 'categories') {
                // Get categories
                $categories = $product->getCategories();
                echo json_encode(['success' => true, 'categories' => $categories]);
            } else {
                // Get products with filters
                $filters = [
                    'category_id' => $_GET['category_id'] ?? null,
                    'search' => $_GET['search'] ?? null,
                    'min_price' => $_GET['min_price'] ?? null,
                    'max_price' => $_GET['max_price'] ?? null,
                    'in_stock' => isset($_GET['in_stock']) ? (bool)$_GET['in_stock'] : null,
                    'order_by' => $_GET['order_by'] ?? 'created_at',
                    'order_dir' => $_GET['order_dir'] ?? 'DESC',
                    'page' => $_GET['page'] ?? 1,
                    'per_page' => $_GET['per_page'] ?? PRODUCTS_PER_PAGE
                ];

                $products = $product->getProducts($filters);
                $total = $product->getProductsCount($filters);

                foreach ($products as &$p) {
                    $p['price'] = $b2b->calculateProductPrice($p, $userId);
                }

                echo json_encode([
                    'success' => true,
                    'products' => $products,
                    'total' => $total,
                    'page' => $filters['page'],
                    'per_page' => $filters['per_page']
                ]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

