<?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') {
    $id       = $_POST['id'] ?? '';
    $trade_id = $_POST['trade_id'] ?? '';
    $kyc_type = $_POST['kyc_type'] ?? '';

    // ✅ Decide record selection
    if (!empty($id)) {
        $check = $conn->prepare("SELECT * FROM kycupload WHERE id=?");
        $check->bind_param("i", $id);
    } elseif (!empty($trade_id)) {
        $check = $conn->prepare("SELECT * FROM kycupload WHERE trade_id=? ORDER BY id DESC LIMIT 1");
        $check->bind_param("s", $trade_id);
    } else {
        echo json_encode(["success" => false, "message" => "❌ Either ID or Trade ID is required"]);
        exit;
    }

    $check->execute();
    $result = $check->get_result();
    $row = $result->fetch_assoc();
    $check->close();

    if (!$row) {
        echo json_encode(["success" => false, "message" => "❌ Record not found"]);
        exit;
    }

    // ✅ Use old values as defaults
    $trade_id     = !empty($trade_id) ? $trade_id : $row['trade_id'];
    $kyc_type     = !empty($kyc_type) ? $kyc_type : $row['kyc_type'];
    $frontFile    = $row['front_image'];
    $backFile     = $row['back_image'];
    $addressFile  = $row['address_proof'];

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

    // ✅ Replace if new files uploaded
    if (isset($_FILES['front_image']) && $_FILES['front_image']['error'] === 0) {
        $frontFile = uniqid("front_") . "_" . basename($_FILES['front_image']['name']);
        move_uploaded_file($_FILES['front_image']['tmp_name'], $uploadDir . $frontFile);
    }
    if (isset($_FILES['back_image']) && $_FILES['back_image']['error'] === 0) {
        $backFile = uniqid("back_") . "_" . basename($_FILES['back_image']['name']);
        move_uploaded_file($_FILES['back_image']['tmp_name'], $uploadDir . $backFile);
    }
    if (isset($_FILES['address_proof']) && $_FILES['address_proof']['error'] === 0) {
        $addressFile = uniqid("address_") . "_" . basename($_FILES['address_proof']['name']);
        move_uploaded_file($_FILES['address_proof']['tmp_name'], $uploadDir . $addressFile);
    }

    // ✅ Always keep labels in text columns
    $kyc_frontside = "frontside";
    $kyc_backside  = "reverseside";

    $stmt = $conn->prepare("UPDATE kycupload 
        SET trade_id=?, kyc_type=?, kyc_frontside=?, front_image=?, 
            kyc_backside=?, back_image=?, address_proof=? 
        WHERE id=?");

    $stmt->bind_param("sssssssi", 
        $trade_id, $kyc_type, $kyc_frontside, $frontFile, 
        $kyc_backside, $backFile, $addressFile, $row['id']
    );

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

    $stmt->close();
}

echo json_encode($response);
