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

// Ensure PHP logs go to local file
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id      = $_SESSION['user']['id'] ?? ($_POST['user_id'] ?? null);
    $kyc_type     = $_POST['kyc_type'] ?? '';
    $address_type = $_POST['address_type'] ?? null;

    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 + name
    $stmtAcc = $conn->prepare("SELECT email, first_name, last_name FROM loginusers WHERE id = ? LIMIT 1");
    $stmtAcc->bind_param("i", $user_id);
    $stmtAcc->execute();
    $resAcc = $stmtAcc->get_result()->fetch_assoc();
    $stmtAcc->close();

    $email     = $resAcc['email'] ?? null;
    $firstName = $resAcc['first_name'] ?? '';
    $lastName  = $resAcc['last_name'] ?? '';
    $fullName  = trim($firstName . ' ' . $lastName);

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

    $kyc_frontside = $frontFile ? "frontside" : null;
    $kyc_backside  = $backFile ? "reverseside" : null;

    // Insert record
    $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()) {
        $reference_id = $stmt->insert_id;
        $stmt->close();

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

        // Build document list string
        $docs = [];
        if (!empty($kyc_type)) $docs[] = $kyc_type;
        if ($addressFile) $docs[] = $address_type ? "Address Proof - $address_type" : "Address Proof";
        if (empty($docs)) $docs[] = 'ID Document, Address Proof';
        $document_list = implode(', ', $docs);

        // ✅ Call your mail function with logging
        $emailSent = false;
        if (defined('EMAIL_AUTOMATION_ENABLED') && EMAIL_AUTOMATION_ENABLED && function_exists('getMailSystem')) {
            try {
                $mailSystem = getMailSystem();

                error_log("[KYC EMAIL] Sending email for user_id={$user_id}, email={$email}, ref={$reference_id}, docs={$document_list}");

                $emailResult = $mailSystem->sendKYCUpload($email, $fullName ?: $email, $reference_id, $document_list);

                if (is_array($emailResult)) {
                    $emailSent = (bool)($emailResult['success'] ?? false);
                    error_log("[KYC EMAIL] sendKYCUpload returned array: " . json_encode($emailResult));
                } elseif (is_bool($emailResult)) {
                    $emailSent = $emailResult;
                    error_log("[KYC EMAIL] sendKYCUpload returned bool: " . ($emailResult ? "true" : "false"));
                } else {
                    error_log("[KYC EMAIL] sendKYCUpload returned unexpected type: " . gettype($emailResult));
                }

                if (!$emailSent && is_object($mailSystem) && method_exists($mailSystem, 'getLastError')) {
                    $lastErr = $mailSystem->getLastError();
                    error_log("[KYC EMAIL] MailSystem::getLastError => " . (is_string($lastErr) ? $lastErr : json_encode($lastErr)));
                }
            } catch (Throwable $e) {
                error_log("[KYC EMAIL] Exception while sending email: " . $e->getMessage());
            }
        }

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

echo json_encode($response);
