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

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

require_once __DIR__ . '/db.php';

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

// Parse path
$request_uri = $_SERVER['REQUEST_URI'];
$path = str_replace('/api_proxy.php', '', parse_url($request_uri, PHP_URL_PATH));
$path = ltrim($path, '/');
$parts = explode('/', $path);
$resource = $parts[0] ?? '';
$id = $parts[1] ?? null;

// Route requests
switch ($resource) {
    case 'test':
        echo json_encode(["message" => "API Proxy is working!"]);
        break;
        
    case 'products':
        handleProducts($conn, $method, $id, $_GET, $input);
        break;
        
    case 'orders':
        handleOrders($conn, $method, $id, $_GET, $input);
        break;
        
    case 'categories':
        handleCategories($conn);
        break;
        
    case 'attributes':
        handleAttributes($conn);
        break;
        
    case 'delivery-companies':
        handleDeliveryCompanies($conn);
        break;
        
    default:
        echo json_encode(["message" => "API Proxy is working!", "resource" => $resource]);
}

$conn->close();

// ==================== PRODUCTS HANDLERS ====================
function handleProducts($conn, $method, $id, $get, $input) {
    if ($method === 'GET') {
        if ($id) {
            getSingleProduct($conn, $id);
        } else {
            getAllProducts($conn, $get);
        }
    } elseif ($method === 'POST') {
        if ($id && strpos($id, 'update')) {
            updateProduct($conn, $input);
        } else {
            addProduct($conn, $input, $_FILES);
        }
    } elseif ($method === 'DELETE' && $id) {
        deleteProduct($conn, $id);
    }
}

function getAllProducts($conn, $params) {
    $search = $params['search'] ?? '';
    $filter_cat = $params['filter_cat'] ?? 0;
    $filter_stat = $params['filter_stat'] ?? 'all';
    $sort = $params['sort'] ?? 'newest';
    
    $sql = "SELECT p.*, c.name AS category_name 
            FROM products p 
            LEFT JOIN categories c ON p.category_id = c.id 
            WHERE 1=1";
    
    $bindParams = [];
    $types = "";
    
    if ($search) {
        $sql .= " AND (p.name LIKE ? OR c.name LIKE ?)";
        $bindParams[] = "%$search%";
        $bindParams[] = "%$search%";
        $types .= "ss";
    }
    if ($filter_cat && $filter_cat > 0) {
        $sql .= " AND p.category_id = ?";
        $bindParams[] = $filter_cat;
        $types .= "i";
    }
    if ($filter_stat === 'active') {
        $sql .= " AND p.is_active = 1";
    } elseif ($filter_stat === 'inactive') {
        $sql .= " AND p.is_active = 0";
    }
    
    switch($sort) {
        case 'price_asc': $sql .= " ORDER BY p.price ASC"; break;
        case 'price_desc': $sql .= " ORDER BY p.price DESC"; break;
        default: $sql .= " ORDER BY p.created_at DESC";
    }
    
    $stmt = $conn->prepare($sql);
    if (!empty($bindParams)) {
        $stmt->bind_param($types, ...$bindParams);
    }
    $stmt->execute();
    $products = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get categories
    $catResult = $conn->query("SELECT id, name FROM categories ORDER BY name");
    $categories = $catResult->get_result()->fetch_all(MYSQLI_ASSOC);
    
    echo json_encode([
        "products" => $products,
        "categories" => $categories,
        "variantsMap" => [],
        "stats" => [
            "total" => count($products),
            "active" => count(array_filter($products, fn($p) => $p['is_active'])),
            "featured" => count(array_filter($products, fn($p) => $p['is_featured'])),
            "low_stock" => 0,
            "out_stock" => 0
        ]
    ]);
}

function getSingleProduct($conn, $id) {
    $stmt = $conn->prepare("
        SELECT p.*, c.name as category_name 
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE p.id = ?
    ");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $product = $stmt->get_result()->fetch_assoc();
    
    // Get images
    $imgStmt = $conn->prepare("SELECT id, image_url, is_primary FROM product_images WHERE product_id = ?");
    $imgStmt->bind_param("i", $id);
    $imgStmt->execute();
    $images = $imgStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Get delivery companies
    $dcStmt = $conn->prepare("SELECT delivery_company_id FROM product_delivery_companies WHERE product_id = ?");
    $dcStmt->bind_param("i", $id);
    $dcStmt->execute();
    $delivery = $dcStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $delivery_companies = array_column($delivery, 'delivery_company_id');
    
    // Get variants
    $varStmt = $conn->prepare("SELECT * FROM product_variants WHERE product_id = ?");
    $varStmt->bind_param("i", $id);
    $varStmt->execute();
    $variants = $varStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    echo json_encode([
        "product" => $product,
        "images" => $images,
        "delivery_companies" => $delivery_companies,
        "variants" => $variants
    ]);
}

function addProduct($conn, $data, $files) {
    // Insert product
    $stmt = $conn->prepare("
        INSERT INTO products (name, description, price, purchase_price, category_id, is_active) 
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("ssddii", 
        $data['name'], 
        $data['description'], 
        $data['base_price'], 
        $data['purchase_price'], 
        $data['category_id'], 
        $data['is_active']
    );
    $stmt->execute();
    $productId = $conn->insert_id;
    
    echo json_encode(["success" => true, "message" => "Product added successfully", "product_id" => $productId]);
}

function updateProduct($conn, $data) {
    $stmt = $conn->prepare("
        UPDATE products SET 
            name = ?, 
            description = ?, 
            price = ?, 
            purchase_price = ?, 
            category_id = ?, 
            is_active = ?
        WHERE id = ?
    ");
    $stmt->bind_param("ssddiii", 
        $data['name'], 
        $data['description'], 
        $data['base_price'], 
        $data['purchase_price'], 
        $data['category_id'], 
        $data['is_active'],
        $data['product_id']
    );
    $stmt->execute();
    
    echo json_encode(["success" => true, "message" => "Product updated successfully"]);
}

function deleteProduct($conn, $id) {
    $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    
    echo json_encode(["success" => true, "message" => "Product deleted successfully"]);
}

// ==================== ORDERS HANDLERS ====================
function handleOrders($conn, $method, $id, $get, $input) {
    if ($method === 'GET') {
        if ($id) {
            getSingleOrder($conn, $id);
        } else {
            getAllOrders($conn, $get);
        }
    } elseif ($method === 'POST') {
        updateOrderStatus($conn, $input);
    }
}

function getAllOrders($conn, $params) {
    $filter = $params['filter'] ?? 'all';
    $search = $params['search'] ?? '';
    
    $sql = "
        SELECT o.*, os.name as status_name, w.name as wilaya_name
        FROM orders o
        LEFT JOIN order_statuses os ON o.status_id = os.id
        LEFT JOIN wilayas w ON o.wilaya_id = w.id
        WHERE 1=1
    ";
    
    if ($search) {
        $sql .= " AND (o.customer_name LIKE '%$search%' OR o.phone LIKE '%$search%')";
    }
    if ($filter !== 'all') {
        $statusMap = ['pending' => 1, 'sent' => 2, 'delivered' => 3];
        if (isset($statusMap[$filter])) {
            $sql .= " AND o.status_id = " . $statusMap[$filter];
        }
    }
    
    $sql .= " ORDER BY o.order_date DESC";
    
    $result = $conn->query($sql);
    $orders = $result->fetch_all(MYSQLI_ASSOC);
    
    echo json_encode([
        "orders" => $orders,
        "orderItems" => [],
        "orderTotals" => [],
        "stats" => [
            "total" => count($orders),
            "pending" => count(array_filter($orders, fn($o) => $o['status_id'] == 1)),
            "sent" => count(array_filter($orders, fn($o) => $o['status_id'] == 2)),
            "delivered" => count(array_filter($orders, fn($o) => $o['status_id'] == 3)),
            "cancelled" => count(array_filter($orders, fn($o) => $o['status_id'] == 4)),
            "revenue" => 0,
            "today" => 0
        ]
    ]);
}

function getSingleOrder($conn, $id) {
    $stmt = $conn->prepare("
        SELECT o.*, w.name as wilaya_name
        FROM orders o
        LEFT JOIN wilayas w ON o.wilaya_id = w.id
        WHERE o.id = ?
    ");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    
    echo json_encode(["order" => $order, "items" => []]);
}

function updateOrderStatus($conn, $data) {
    $stmt = $conn->prepare("UPDATE orders SET status_id = ? WHERE id = ?");
    $stmt->bind_param("ii", $data['status_id'], $data['order_id']);
    $stmt->execute();
    
    echo json_encode(["success" => true, "message" => "Status updated"]);
}

// ==================== HELPERS ====================
function handleCategories($conn) {
    $result = $conn->query("SELECT id, name FROM categories ORDER BY name");
    echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}

function handleAttributes($conn) {
    $result = $conn->query("SELECT * FROM attributes ORDER BY name");
    echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}

function handleDeliveryCompanies($conn) {
    $result = $conn->query("SELECT id, name FROM delivery_companies ORDER BY name");
    echo json_encode($result->fetch_all(MYSQLI_ASSOC));
}
?>