<?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(); // Start session
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);
    $kyc_type     = $_POST['kyc_type'] ?? '';
    $address_type = $_POST['address_type'] ?? null; // ✅ Added

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

    // Fetch email from liveaccounts using user_id
    $stmtAcc = $conn->prepare("SELECT email FROM liveaccounts WHERE user_id = ? LIMIT 1");
    $stmtAcc->bind_param("i", $user_id);
    $stmtAcc->execute();
    $resAcc = $stmtAcc->get_result()->fetch_assoc();
    $stmtAcc->close();

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

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

    $frontFile   = null;
    $backFile    = null;
    $addressFile = null;

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

    // Labels (optional)
    $kyc_frontside = $frontFile ? "frontside" : null;
    $kyc_backside  = $backFile ? "reverseside" : null;

    // Insert new record including address_type
    $stmt = $conn->prepare("INSERT INTO kycupload 
        (user_id, email, kyc_type, kyc_frontside, front_image, kyc_backside, back_image, address_proof, address_type, Status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");
    
    $stmt->bind_param(
        "issssssss",
        $user_id,
        $email,
        $kyc_type,
        $kyc_frontside,
        $frontFile,
        $kyc_backside,
        $backFile,
        $addressFile,
        $address_type
    );

    if ($stmt->execute()) {
        // Update loginusers.kyc_status = 1
        $update = $conn->prepare("UPDATE loginusers SET kyc_status = 1 WHERE id = ?");
        $update->bind_param("i", $user_id);
        $update->execute();
        $update->close();

        $response = ["success" => true, "message" => "✅ KYC uploaded successfully & status updated"];
    } else {
        $response = ["success" => false, "message" => "DB Error: " . $stmt->error];
    }

    $stmt->close();
}

echo json_encode($response);
