<?php
// api/product_detail.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

require_once __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../inc/functions.php'; // for send_json() & get_post_data()

// ---------------------------------------------------------
// 1️⃣  Read JSON body and get product_id
// ---------------------------------------------------------
$data = get_post_data();   // reads php://input and json_decodes
$product_id = isset($data['id']) ? (int)$data['id'] : 0;

if ($product_id <= 0) {
    send_json(['status' => false, 'msg' => 'Missing or invalid product id']);
}

// ---------------------------------------------------------
// 2️⃣  Optional: Token authentication
// ---------------------------------------------------------
$token = '';
if (!empty($_SERVER['HTTP_AUTHORIZATION']) &&
    preg_match('/Bearer\s+(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $m)) {
    $token = $m[1];
}
if (!$token && !empty($data['token'])) {     // allow token in JSON too
    $token = $data['token'];
}

if (!$token) {
    send_json(['status' => false, 'msg' => 'Missing API token']);
}

$stmt = $conn->prepare("SELECT id FROM users WHERE api_token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
if (!$stmt->get_result()->fetch_assoc()) {
    send_json(['status' => false, 'msg' => 'Invalid token']);
}
$stmt->close();

// ---------------------------------------------------------
// 3️⃣  Fetch product details by id
// ---------------------------------------------------------
$sql = "SELECT * FROM products WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $product_id);
$stmt->execute();
$res = $stmt->get_result();
$product = $res->fetch_assoc();
$stmt->close();

if (!$product) {
    send_json(['status' => false, 'msg' => 'Product not found']);
}

// Decode JSON column for images
$product['images'] = json_decode($product['images'], true);

// ---------------------------------------------------------
// 4️⃣  Return JSON
// ---------------------------------------------------------
send_json([
    'status'  => true,
    'msg'     => 'Product detail fetched',
    'product' => $product
]);
