<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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();
include_once __DIR__ . '/config.php';
include_once __DIR__ . '/connection.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get POST values directly
    $user_id  = $_POST['user_id'] ?? '';
    $kyc_type = $_POST['kyc_type'] ?? '';

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

    // Check database connection
    if (!$conn) {
        echo json_encode(["success" => false, "message" => "❌ DB connection failed"]);
        exit;
    }

    // Fetch user email
    $stmtAcc = $conn->prepare("SELECT email FROM liveaccounts WHERE user_id = ? LIMIT 1");
    if (!$stmtAcc) {
        echo json_encode(["success" => false, "message" => "❌ DB prepare error: " . $conn->error]);
        exit;
    }

    $stmtAcc->bind_param("i", $user_id);
    $stmtAcc->execute();
    $resAcc = $stmtAcc->get_result();
    if (!$resAcc) {
        echo json_encode(["success" => false, "message" => "❌ DB get_result error: " . $stmtAcc->error]);
        exit;
    }

    $resAcc = $resAcc->fetch_assoc();
    $stmtAcc->close();

    $email = $resAcc['email'] ?? null;
    if (empty($email)) {
        echo json_encode(["success" => false, "message" => "❌ User not found"]);
        exit;
    }

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

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

    // Generate unique 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']);

    if (!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)) {
        echo json_encode(["success" => false, "message" => "❌ File upload failed. Check permissions."]);
        exit;
    }

    $kyc_frontside = "frontside";
    $kyc_backside  = "reverseside";

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

    if (!$stmt) {
        echo json_encode(["success" => false, "message" => "❌ DB prepare error: " . $conn->error]);
        exit;
    }

    $stmt->bind_param(
    "isssssss",
    $user_id,
    $email,
    $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);
