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

session_start(); // ✅ Make sure session is started
include_once __DIR__ . '/config.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get user_id from session or POST
    $user_id  = $_SESSION['user']['id'] ?? ($_POST['user_id'] ?? null);
    $id       = $_POST['id'] ?? '';
    $trade_id = $_POST['trade_id'] ?? '';
    $kyc_type = $_POST['kyc_type'] ?? '';

    if (empty($user_id)) {
        echo json_encode(["success" => false, "message" => "❌ User ID missing"]);
        exit;
    }

    // Decide which record to update
    if (!empty($id)) {
        $check = $conn->prepare("SELECT * FROM kycupload WHERE id=? AND user_id=?");
        $check->bind_param("ii", $id, $user_id);
    } elseif (!empty($trade_id)) {
        $check = $conn->prepare("SELECT * FROM kycupload WHERE trade_id=? AND user_id=? ORDER BY id DESC LIMIT 1");
        $check->bind_param("si", $trade_id, $user_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);
    }

    // Keep labels in text columns
    $kyc_frontside = "frontside";
    $kyc_backside  = "reverseside";

    // ✅ Correct bind_param type string: 7 strings + 2 integers
    $stmt = $conn->prepare("UPDATE kycupload 
        SET trade_id=?, kyc_type=?, kyc_frontside=?, front_image=?, 
            kyc_backside=?, back_image=?, address_proof=?
        WHERE id=? AND user_id=?");

    $stmt->bind_param(
        "sssssssii",
        $trade_id,
        $kyc_type,
        $kyc_frontside,
        $frontFile,
        $kyc_backside,
        $backFile,
        $addressFile,
        $row['id'],
        $user_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);
