<?php
// 1. Clear out any previous server crash tracking flags
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

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

// 2. Safely connect your backend configuration layout
require_once '../config/database.php';

$db = getDB();
$sections = [];

// FIXED FALLBACK: Updated to match your true app asset domain path
if (!defined('BASE_URL')) {
    define('BASE_URL', 'https://probashipriyo.store/api/');
}

// 3. Query active homepage sections sequentially
$sectionQuery = $db->query("
    SELECT *
    FROM product_sections
    WHERE is_active = 1
    ORDER BY id ASC
");

if (!$sectionQuery) {
    echo json_encode([
        "success" => false, 
        "message" => "Sections query failed: " . $db->error
    ]);
    exit;
}

while ($section = $sectionQuery->fetch_assoc()) {
    $sectionId = intval($section['id']);
    $products = [];

    // 4. Fetch the existing active items bound to this homepage slot
    $productQuery = $db->query("
        SELECT p.* FROM section_products sp
        INNER JOIN products p ON p.id = sp.product_id
        WHERE sp.section_id = $sectionId 
          AND p.is_active = 1
        ORDER BY p.id DESC
    ");

    if (!$productQuery) {
        continue;
    }

    while ($row = $productQuery->fetch_assoc()) {
        $fullImages = [];

        // 5. Unpack structural file assets (CRASH-PROOF FALLBACK FOR PLAIN TEXT vs JSON ENCODED ARRAYS)
        if (!empty($row['images'])) {
            $images = json_decode($row['images'], true);
            
            if (is_array($images)) {
                // Scenario A: It's a valid JSON array -> ["burger.jpg"]
                foreach ($images as $img) {
                    $cleanImg = str_replace('uploads/products/', '', $img);
                    $fullImages[] = BASE_URL . "uploads/products/" . $cleanImg;
                }
            } else {
                // Scenario B: It's a plain text string fallback -> burger.jpg
                $cleanImg = str_replace('uploads/products/', '', $row['images']);
                $fullImages[] = BASE_URL . "uploads/products/" . $cleanImg;
            }
        }

        // 6. Calculate relative timing banners safely
        $isNewProduct = 0;
        if (!empty($row['created_at'])) {
            $timestamp = strtotime($row['created_at']);
            if ($timestamp !== false) {
                $isNewProduct = ($timestamp > strtotime('-4 weeks')) ? 1 : 0;
            }
        }

        // 7. Establish clean field assignments for your Flutter JSON map parser
        $products[] = [
            "id"             => intval($row['id']),
            "category_id"    => intval($row['category_id'] ?? 0),
            "name_en"        => $row['name_en'] ?? '',
            "name_bn"        => $row['name_bn'] ?? '',
            "description_en" => $row['description_en'] ?? '',
            "description_bn" => $row['description_bn'] ?? '',
            "price"          => floatval($row['price'] ?? 0),
            "old_price"      => (!empty($row['old_price']) && floatval($row['old_price']) > 0) ? floatval($row['old_price']) : null,
            "stock"          => intval($row['stock'] ?? 0),
            "avg_rating"     => isset($row['avg_rating']) ? floatval($row['avg_rating']) : 0.0,
            "review_count"   => isset($row['review_count']) ? intval($row['review_count']) : 0,
            "is_featured"    => isset($row['is_featured']) ? intval($row['is_featured']) : 0,
            "is_new"         => $isNewProduct,
            "total_sales"    => isset($row['total_sales']) ? intval($row['total_sales']) : 0,
            "created_at"     => $row['created_at'] ?? '',
            "images"         => $fullImages,
        ];
    }

    // Append section arrays only if active matched elements exist inside them
    if (count($products) > 0) {
        $sections[] = [
            "id"       => intval($section['id']),
            "title_en" => $section['title_en'] ?? '',
            "title_bn" => $section['title_bn'] ?? '',
            "slug"     => $section['slug'] ?? '',
            "products" => $products,
        ];
    }
}

// 8. Output data packet clean back to Dart network channel
echo json_encode([
    "success" => true,
    "data" => [
        "sections" => $sections
    ]
]);