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

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

// Only allow GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    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()

// ---------------------
// Get API token
// ---------------------
$token = '';

// 1) Check Authorization header:  Authorization: Bearer <token>
if (!empty($_SERVER['HTTP_AUTHORIZATION']) &&
    preg_match('/Bearer\s+(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $m)) {
    $token = $m[1];
}

// 2) Some servers use REDIRECT_HTTP_AUTHORIZATION
if (!$token && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) &&
    preg_match('/Bearer\s+(\S+)/', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $m)) {
    $token = $m[1];
}

// 3) Query parameter ?token=...
if (!$token && isset($_GET['token'])) {
    $token = trim($_GET['token']);
}

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

// ---------------------
// Validate token
// ---------------------
$stmt = $conn->prepare("SELECT id, name, email 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'
    ]);
}

// ---------------------
// Fetch all products
// ---------------------
$products = [];
$result = $conn->query("SELECT * FROM products ORDER BY id ASC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        // decode JSON in 'images' column (if present)
        $row['images'] = json_decode($row['images'], true);
        $products[] = $row;
    }
}

// ---------------------
// Output JSON
// ---------------------
send_json([
    'status'   => true,
    'msg'      => 'Product list fetched',
    'products' => $products
]);
