<?php

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

// Disable error display in output to ensure clean JSON parsing
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

require_once '../config/database.php';

$db = getDB();

$productId = intval($_GET['id'] ?? 0);

if ($productId <= 0) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid Product ID"
    ]);
    exit;
}

// Ensure BASE_URL is defined locally if not loaded globally from database.php
if (!defined('BASE_URL')) {
    define('BASE_URL', 'https://globinvest.online/api/');
}

$productQuery = $db->query("
    SELECT
        p.*,
        c.name_en as category_name_en,
        c.name_bn as category_name_bn
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    WHERE p.id = $productId
    LIMIT 1
");

if ($productQuery->num_rows == 0) {
    echo json_encode([
        "success" => false,
        "message" => "Product Not Found"
    ]);
    exit;
}

$product = $productQuery->fetch_assoc();


// =====================
// GALLERY (FIXED PLAIN TEXT VS JSON ARRAY FALLBACK)
// =====================
$gallery = [];
if (!empty($product['images'])) {
    $images = json_decode($product['images'], true);

    if (is_array($images)) {
        // If stored as JSON array: ["pizza.jpg", "pizza2.jpg"]
        foreach ($images as $img) {
            $cleanImg = str_replace('uploads/products/', '', $img);
            $gallery[] = BASE_URL . "uploads/products/" . $cleanImg;
        }
    } else {
        // Fallback if stored as plain string text: "pizza.jpg"
        $cleanImg = str_replace('uploads/products/', '', $product['images']);
        $gallery[] = BASE_URL . "uploads/products/" . $cleanImg;
    }
}


// =====================
// REVIEWS
// =====================
$reviews = [];
$totalRating = 0;

$reviewQuery = $db->query("
    SELECT *
    FROM product_reviews
    WHERE product_id = $productId
    ORDER BY id DESC
");

while ($review = $reviewQuery->fetch_assoc()) {
    $totalRating += intval($review['rating']);
    $reviews[] = [
        "name" => $review['customer_name'] ?? 'Customer',
        "review" => $review['review'] ?? '',
        "rating" => intval($review['rating']),
    ];
}

$avgRating = 0;
if (count($reviews) > 0) {
    $avgRating = round($totalRating / count($reviews), 1);
} else {
    // Default fallback rating if no reviews exist yet
    $avgRating = floatval($product['avg_rating'] ?? 4.9);
}


// =====================
// RELATED PRODUCTS (FIXED IMAGE PARSING TOO)
// =====================
$related = [];
$relatedQuery = $db->query("
    SELECT *
    FROM products
    WHERE category_id = " . intval($product['category_id']) . "
    AND id != $productId
    LIMIT 10
");

while ($row = $relatedQuery->fetch_assoc()) {
    $imgList = [];

    if (!empty($row['images'])) {
        $imgs = json_decode($row['images'], true);

        if (is_array($imgs)) {
            foreach ($imgs as $img) {
                $cleanImg = str_replace('uploads/products/', '', $img);
                $imgList[] = BASE_URL . "uploads/products/" . $cleanImg;
            }
        } else {
            $cleanImg = str_replace('uploads/products/', '', $row['images']);
            $imgList[] = BASE_URL . "uploads/products/" . $cleanImg;
        }
    }

    $related[] = [
        "id" => intval($row['id']),
        "category_id" => intval($row['category_id']),
        "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']) : null,
        "stock" => intval($row['stock'] ?? 0),
        "avg_rating" => floatval($row['avg_rating'] ?? 4.9),
        "review_count" => 0,
        "created_at" => $row['created_at'] ?? '',
        "images" => $imgList,
        "image" => (count($imgList) > 0) ? $imgList[0] : "" // Flutter helper field
    ];
}


// =====================
// VARIATIONS
// =====================
$variations = [];
$variationQuery = $db->query("
    SELECT *
    FROM product_variations
    WHERE product_id = $productId
");

while ($v = $variationQuery->fetch_assoc()) {
    $variations[] = [
        "type" => $v['variation_type'] ?? '',
        "value" => $v['variation_value'] ?? '',
    ];
}


// =====================
// FINAL RESPONSE
// =====================
echo json_encode([
    "success" => true,
    "data" => [
        "id" => intval($product['id']),
        "category_id" => intval($product['category_id']),
        "category_name_en" => $product['category_name_en'] ?? '',
        "category_name_bn" => $product['category_name_bn'] ?? '',
        "name_en" => $product['name_en'] ?? '',
        "name_bn" => $product['name_bn'] ?? '',
        "description_en" => $product['description_en'] ?? '',
        "description_bn" => $product['description_bn'] ?? '',
        "price" => floatval($product['price'] ?? 0),
        "old_price" => !empty($product['old_price']) ? floatval($product['old_price']) : null,
        "stock" => intval($product['stock'] ?? 0),
        "total_sales" => intval($product['total_sales'] ?? 0),
        "avg_rating" => $avgRating,
        "review_count" => count($reviews),
        "created_at" => $product['created_at'] ?? '',
        "image" => (count($gallery) > 0) ? $gallery[0] : "", // CRITICAL: This is what Flutter uses for single image binding!
        "images" => $gallery,
        "gallery" => $gallery,
        "variations" => $variations,
        "reviews" => $reviews,
        "related_products" => $related,
    ]
]);