<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

include_once __DIR__ . '/config.php';

$response = ["success" => false, "message" => "Something went wrong"];

// ✅ Log everything coming in
file_put_contents("debug.log", "\n--- NEW REQUEST ---\n", FILE_APPEND);
file_put_contents("debug.log", "POST: " . print_r($_POST, true) . "\n", FILE_APPEND);
file_put_contents("debug.log", "FILES: " . print_r($_FILES, true) . "\n", FILE_APPEND);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $trade_id = $_POST['trade_id'] ?? '';
    $kyc_type = $_POST['kyc_type'] ?? '';

    // ✅ Explicit error responses
    if (empty($trade_id)) {
        echo json_encode(["success" => false, "message" => "❌ Trade ID missing"]);
        exit;
    }
    if (empty($kyc_type)) {
        echo json_encode(["success" => false, "message" => "❌ KYC Type missing"]);
        exit;
    }
    if (!isset($_FILES['front_image'])) {
        echo json_encode(["success" => false, "message" => "❌ Front image missing"]);
        exit;
    }
    if (!isset($_FILES['back_image'])) {
        echo json_encode(["success" => false, "message" => "❌ Back image missing"]);
        exit;
    }

    $uploadDir = __DIR__ . "/uploads/kyc/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    $frontFile = uniqid("front_") . "_" . basename($_FILES['front_image']['name']);
    $backFile  = uniqid("back_") . "_" . basename($_FILES['back_image']['name']);

    move_uploaded_file($_FILES['front_image']['tmp_name'], $uploadDir . $frontFile);
    move_uploaded_file($_FILES['back_image']['tmp_name'], $uploadDir . $backFile);

    $stmt = $conn->prepare("INSERT INTO kycupload 
        (trade_id, kyc_type, kyc_frontside, front_image, kyc_backside, back_image, Status) 
        VALUES (?, ?, ?, ?, ?, ?, 0)");

    $stmt->bind_param("ssssss", $trade_id, $kyc_type, $frontFile, $frontFile, $backFile, $backFile);

    if ($stmt->execute()) {
        $response = ["success" => true, "message" => "✅ KYC uploaded successfully"];
    } else {
        $response = ["success" => false, "message" => "DB Error: " . $stmt->error];
    }

    $stmt->close();
}

echo json_encode($response);
