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

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors',1);

require 'db_connect.php'; 

header('Content-Type: application/json');
ob_clean();

$response = [];

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

if (!isset($_GET['id']) || empty($_GET['id'])) {
    http_response_code(400); 
    $response['status'] = 'error';
    $response['message'] = 'Product ID is missing.';
    echo json_encode($response);
    exit;
}

$product_id = intval($_GET['id']);

try {
    $sql = "SELECT 
                p.id, p.name, p.category, p.brand_id, b.name AS brand_name, 
                p.models, p.description, p.specification, 
                p.regular_price, p.offer_price, p.image_url, p.gallery_images, p.is_featured,
                COALESCE(AVG(r.rating), 0) AS rating,
                COUNT(r.id) AS total_reviews
            FROM products p
            LEFT JOIN brands b ON p.brand_id = b.id
            LEFT JOIN reviews r ON p.id = r.product_id AND r.status = 'Published'
            WHERE p.id = ?
            GROUP BY p.id";

    $stmt = $conn->prepare($sql);

    if ($stmt) {
        $stmt->bind_param("i", $product_id);
        
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $product = $result->fetch_assoc();
                
                // --- DATA TYPE CASTING FIX ---
                $product['id'] = (int)$product['id'];
                $product['brand_id'] = (int)$product['brand_id'];
                $product['regular_price'] = (float)$product['regular_price'];
                $product['offer_price'] = (float)$product['offer_price'];
                $product['rating'] = (float)$product['rating'];
                $product['total_reviews'] = (int)$product['total_reviews'];
                $product['is_featured'] = (int)$product['is_featured']; // This is the critical fix
                
                // Fetch reviews separately
                $reviews = [];
                $review_stmt = $conn->prepare("SELECT * FROM reviews WHERE product_id = ? AND status = 'Published'");
                $review_stmt->bind_param("i", $product_id);
                $review_stmt->execute();
                $review_result = $review_stmt->get_result();
                while($review_row = $review_result->fetch_assoc()){
                    $reviews[] = $review_row;
                }
                $product['reviews'] = $reviews;

                echo json_encode($product, JSON_NUMERIC_CHECK);

            } else {
                http_response_code(404);
                $response['status'] = 'error';
                $response['message'] = 'Product not found.';
                echo json_encode($response);
            }
        } else {
            throw new Exception('Query execution failed.');
        }
        $stmt->close();
    } else {
        throw new Exception('Statement preparation failed.');
    }

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: ' . $e->getMessage();
    echo json_encode($response);
}

$finalOutput = ob_get_contents();
ob_clean();
echo $finalOutput;

$conn->close();
exit;
?>