<?php
// api/products/delete_product.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') { 
    http_response_code(200);
    exit; 
}

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

require_once __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../inc/functions.php';

// Debug information
$debug_info = [
    'method' => $_SERVER['REQUEST_METHOD'],
    'has_authorization_header' => isset($_SERVER['HTTP_AUTHORIZATION']),
    'authorization_header' => $_SERVER['HTTP_AUTHORIZATION'] ?? 'not set',
    'has_redirect_authorization' => isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']),
    'redirect_authorization' => $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? 'not set',
    'post_data' => $_POST,
    'all_headers' => function_exists('getallheaders') ? getallheaders() : 'getallheaders not available',
];

// Get API token from multiple sources
$token = '';

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

// 2. Check REDIRECT_HTTP_AUTHORIZATION (some servers use this)
if (!$token && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    if (preg_match('/Bearer\s+(\S+)/', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $m)) {
        $token = $m[1];
        $debug_info['token_source'] = 'REDIRECT_HTTP_AUTHORIZATION header';
    }
}

// 3. Check getallheaders() function
if (!$token && function_exists('getallheaders')) {
    $headers = getallheaders();
    if (isset($headers['Authorization'])) {
        if (preg_match('/Bearer\s+(\S+)/', $headers['Authorization'], $m)) {
            $token = $m[1];
            $debug_info['token_source'] = 'getallheaders() function';
        }
    }
}

// 4. Check POST data
if (!$token && isset($_POST['token'])) {
    $token = trim($_POST['token']);
    $debug_info['token_source'] = 'POST data';
}

// 5. Check JSON body
if (!$token) {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!empty($input['token'])) {
        $token = trim($input['token']);
        $debug_info['token_source'] = 'JSON body';
    }
}

$debug_info['token_received'] = !empty($token);
$debug_info['token_length'] = strlen($token);
$debug_info['token_preview'] = !empty($token) ? substr($token, 0, 10) . '...' : 'none';

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

// 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',
        'debug' => $debug_info
    ]);
}

$debug_info['user_found'] = true;
$debug_info['user_id'] = $user['id'];

// Get product ID
$product_id = 0;
if (isset($_POST['id'])) {
    $product_id = (int)$_POST['id'];
} elseif (isset($_POST['product_id'])) {
    $product_id = (int)$_POST['product_id'];
} else {
    // Check JSON body
    $input = json_decode(file_get_contents('php://input'), true);
    if (!empty($input['id'])) {
        $product_id = (int)$input['id'];
    } elseif (!empty($input['product_id'])) {
        $product_id = (int)$input['product_id'];
    }
}

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

// Check if product exists
$stmt = $conn->prepare("SELECT id, name FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result = $stmt->get_result();
$product = $result->fetch_assoc();
$stmt->close();

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

// Delete the product
$stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);

if ($stmt->execute()) {
    if ($stmt->affected_rows > 0) {
        send_json([
            'status' => true,
            'msg' => 'Product deleted successfully',
            'deleted_product' => [
                'id' => $product['id'],
                'name' => $product['name']
            ]
        ]);
    } else {
        send_json(['status'=>false,'msg'=>'No product was deleted']);
    }
} else {
    send_json(['status'=>false,'msg'=>'Failed to delete product']);
}

$stmt->close();
?>