<?php
// get_home_data.php (FINAL - DATA TYPE FIX)

header('Content-Type: application/json; charset=utf-8');
require 'db_connect.php'; 

$response = array();
$response['status'] = 'error';
$response['message'] = 'An unknown error occurred.';

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

$conn->set_charset("utf8mb4");

try {
    // --- 1. Fetch Sliders ---
    $sliders = array();
    $slider_result = $conn->query("SELECT id, image_url FROM sliders ORDER BY id ASC");
    if ($slider_result) { while ($row = $slider_result->fetch_assoc()) { $sliders[] = $row; } }

    // --- 2. Fetch Categories ---
    $categories = array();
    $category_result = $conn->query("SELECT id, name, image_url FROM categories ORDER BY name ASC");
    if ($category_result) { while ($row = $category_result->fetch_assoc()) { $categories[] = $row; } }

    // --- 3. Fetch Trending Products ---
    $products = array();
    $product_sql = "
        SELECT p.id, p.name, p.regular_price, p.offer_price, p.image_url, p.is_featured,
               COALESCE(AVG(r.rating), 0) AS rating, COUNT(r.id) AS total_reviews
        FROM products p
        LEFT JOIN reviews r ON p.id = r.product_id AND r.status = 'Published'
        GROUP BY p.id ORDER BY p.id ASC LIMIT 150";
    $product_result = $conn->query($product_sql);
    if ($product_result) { while ($row = $product_result->fetch_assoc()) { $products[] = $row; } }

    // --- 4. Fetch Best Deals ---
    $best_deals = array();
    $best_deals_query = "
        SELECT c.name AS category_name, p.id, p.name, p.regular_price, p.offer_price, p.image_url, p.is_featured,
               COALESCE(AVG(r.rating), 0) AS rating, COUNT(r.id) AS total_reviews
        FROM products p
        JOIN categories c ON p.category = c.name
        LEFT JOIN reviews r ON p.id = r.product_id AND r.status = 'Published'
        WHERE c.best_deal = 1
        GROUP BY p.id, c.name ORDER BY c.name, p.id";
    $best_deals_result = $conn->query($best_deals_query);
    if ($best_deals_result) {
        while ($row = $best_deals_result->fetch_assoc()) {
            $categoryName = $row['category_name'];
            if (!isset($best_deals[$categoryName])) { $best_deals[$categoryName] = array(); }
            unset($row['category_name']);
            $best_deals[$categoryName][] = $row;
        }
    }

    // --- 5. Fetch Featured Products ---
    $featured_products = array();
    $featured_sql = "
        SELECT p.id, p.name, p.regular_price, p.offer_price, p.image_url, p.is_featured,
               COALESCE(AVG(r.rating), 0) AS rating, COUNT(r.id) AS total_reviews
        FROM products p
        LEFT JOIN reviews r ON p.id = r.product_id AND r.status = 'Published'
        WHERE p.is_featured = 1
        GROUP BY p.id ORDER BY p.id ASC LIMIT 10";
    $featured_result = $conn->query($featured_sql);
    if ($featured_result) { while ($row = $featured_result->fetch_assoc()) { $featured_products[] = $row; } }

    // --- 6. Fetch Other Data ---
    $promo_banner = $conn->query("SELECT image_url FROM promo_banner LIMIT 1")->fetch_assoc();
    $notice_row = $conn->query("SELECT notice FROM notices ORDER BY id DESC LIMIT 1")->fetch_assoc();
    $popup_banner = $conn->query("SELECT image_url FROM popup_banners LIMIT 1")->fetch_assoc();

    $data = array(
        'sliders' => $sliders,
        'categories' => $categories,
        'products' => $products,
        'bestDeals' => $best_deals,
        'featuredProducts' => $featured_products,
        'promoBanner' => $promo_banner,
        'notice' => $notice_row ? $notice_row['notice'] : null,
        'popupBanner' => $popup_banner
    );

    $response['status'] = 'success';
    $response['message'] = 'Home data fetched successfully.';
    $response['data'] = $data;

} catch (Exception $e) {
    http_response_code(500);
    $response['message'] = 'An exception occurred on the server: ' . $e->getMessage();
}

$conn->close();
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
exit;
?>