<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../db.php';

try {
    $response = [
        'categories' => [],
        'products' => [],
        'user' => null
    ];

    // Check if user is logged in
    if (isset($_SESSION['user_id'])) {
        $stmt = $conn->prepare("SELECT user_id as id, full_name as name, email, role, seller_status FROM users WHERE user_id = ?");
        $stmt->bind_param("i", $_SESSION['user_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($user = $result->fetch_assoc()) {
            $response['user'] = $user;
        }
        $stmt->close();
    }

    // Get categories
    $stmt = $conn->prepare("SELECT category_id as id, category_name as name, icon FROM categories");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $response['categories'][] = $row;
    }
    $stmt->close();

    // Get products (active and approved)
    $stmt = $conn->prepare("
        SELECT 
            product_id as id, 
            category_id as category, 
            product_name as name, 
            description, 
            price, 
            original_price as originalPrice, 
            rating_avg as rating, 
            sold_count as sold, 
            badge, 
            badge_text as badgeText, 
            image_url as image 
        FROM products 
        WHERE is_active = 1 AND approval_status = 'approved'
        ORDER BY created_at DESC
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $row['id'] = (int)$row['id'];
        $row['price'] = (float)$row['price'];
        $row['originalPrice'] = $row['originalPrice'] ? (float)$row['originalPrice'] : null;
        $row['rating'] = (float)$row['rating'];
        $row['sold'] = (int)$row['sold'];
        $row['reviewsCount'] = rand(10, 500); 
        $response['products'][] = $row;
    }
    $stmt->close();

    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error']);
}
?>
