<?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"];

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

    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;
    }

    // ✅ File validations
    if (!isset($_FILES['front_image']) || !isset($_FILES['back_image']) || !isset($_FILES['address_proof'])) {
        echo json_encode([
            "success" => false,
            "message" => "❌ Required files missing (need front, back & address proof)"
        ]);
        exit;
    }

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

    // ✅ File names
    $frontFile   = uniqid("front_") . "_" . basename($_FILES['front_image']['name']);
    $backFile    = uniqid("back_") . "_" . basename($_FILES['back_image']['name']);
    $addressFile = uniqid("address_") . "_" . basename($_FILES['address_proof']['name']);

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

    // ✅ Store only text in `kyc_frontside` & `kyc_backside`, store actual file in respective file columns
    $kyc_frontside = "frontside";
    $kyc_backside  = "reverseside";

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

    $stmt->bind_param("sssssss", $trade_id, $kyc_type, $kyc_frontside, $frontFile, $kyc_backside, $backFile, $addressFile);

    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);
