<?php
// =====================================================
// CORS & Request Method
// =====================================================
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: PUT, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

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

if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    http_response_code(405);
    echo json_encode(['status' => false, 'msg' => 'Method Not Allowed']);
    exit;
}

require_once __DIR__ . '/../inc/db.php';        // $conn = mysqli connection
require_once __DIR__ . '/../inc/functions.php'; // send_json()

// =====================================================
// 1️⃣  Get API Token (Bearer or ?token=)
// =====================================================
$token = '';
if (!empty($_SERVER['HTTP_AUTHORIZATION']) &&
    preg_match('/Bearer\s+(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $m)) {
    $token = $m[1];
}
if (!$token && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) &&
    preg_match('/Bearer\s+(\S+)/', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $m)) {
    $token = $m[1];
}
if (!$token && isset($_GET['token'])) {
    $token = trim($_GET['token']);
}
if (!$token) {
    send_json(['status' => false, 'msg' => 'Missing API token']);
}

// =====================================================
// 2️⃣  Validate Token
// =====================================================
$stmt = $conn->prepare("SELECT id FROM users WHERE api_token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

// =====================================================
// 3️⃣  Parse JSON Input
// =====================================================
$data = json_decode(file_get_contents("php://input"), true);
if (!$data) {
    send_json(['status' => false, 'msg' => 'Invalid JSON input']);
}

$product_id = intval($data['id'] ?? 0);
$name       = trim($data['name'] ?? '');
$price      = floatval($data['price'] ?? 0);
$images     = $data['images'] ?? []; // array of image URLs or paths

if ($product_id <= 0 || $name === '' || $price <= 0) {
    send_json(['status' => false, 'msg' => 'Missing or invalid fields']);
}

// =====================================================
// 4️⃣  Ensure Product Exists (ID Match Check)
// =====================================================
$check = $conn->prepare("SELECT id FROM products WHERE id = ?");
$check->bind_param("i", $product_id);
$check->execute();
if ($check->get_result()->num_rows === 0) {
    $check->close();
    send_json(['status' => false, 'msg' => 'Product not found']);
}
$check->close();

// =====================================================
// 5️⃣  Update Product
// =====================================================
$jsonImages = json_encode($images);
$stmt = $conn->prepare(
    "UPDATE products SET name = ?, price = ?, images = ? WHERE id = ?"
);
$stmt->bind_param("sdsi", $name, $price, $jsonImages, $product_id);
$ok = $stmt->execute();
$stmt->close();

if (!$ok) {
    send_json(['status' => false, 'msg' => 'Update failed']);
}

// =====================================================
// 6️⃣  Return Updated Row
// =====================================================
$stmt = $conn->prepare("SELECT * FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();
$stmt->close();

if ($product && isset($product['images'])) {
    $product['images'] = json_decode($product['images'], true);
}

send_json([
    'status'  => true,
    'msg'     => 'Product updated successfully',
    'product' => $product
]);
