<?php
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();
$db->set_charset("utf8mb4");

// Explicit JOIN maps category fields automatically matching assigned IDs
$productQuery = "SELECT 
                    p.*, 
                    c.name_en AS category_name_en, 
                    c.name_bn AS category_name_bn 
                 FROM products p 
                 LEFT JOIN categories c ON p.category_id = c.id 
                 ORDER BY p.id DESC";

$result = $db->query($productQuery);
$products = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $product_id = intval($row['id']);
        
        // Fetch matching relational home segment sections checkboxes maps
        $sectionQuery = $db->query("SELECT section_id FROM section_products WHERE product_id = $product_id");
        $sectionsArray = [];
        if ($sectionQuery) {
            while ($secRow = $sectionQuery->fetch_assoc()) {
                $sectionsArray[] = intval($secRow['section_id']);
            }
        }
        
        $row['sections_array'] = $sectionsArray;
        
        // Enforce safe clean fallback fallback strings if rows are unassigned
        $row['category_name_en'] = !empty($row['category_name_en']) ? trim($row['category_name_en']) : 'General';
        $row['category_name_bn'] = !empty($row['category_name_bn']) ? trim($row['category_name_bn']) : 'সাধারণ';
        
        // Force fallback default string literal arrays if values are completely null
        $row['images'] = !empty($row['images']) ? trim($row['images']) : '[]';

        $products[] = $row;
    }
}

echo json_encode([
    "success" => true,
    "products" => $products
], JSON_UNESCAPED_UNICODE);