<?php
/**
 * approve_kyc.php: Handles admin approval of KYC submissions
 * Part of Ton Sui Mining KYC workflow
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Surface fatals as JSON to the client for debugging
error_reporting(E_ALL);
ini_set('display_errors', '0');
register_shutdown_function(function () {
    $e = error_get_last();
    if ($e && !headers_sent()) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Fatal: ' . ($e['message'] ?? 'Unknown')]);
    }
});

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

require_once 'config.php';
require_once 'db.php';

$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['id'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing KYC id"]);
    exit;
}

try {
    // Introspect kyc_requests columns to build safe queries
    $hasDocType = false; $hasDocNumber = false; $hasReviewedAt = false; $hasReviewedBy = false;
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM kyc_requests");
        while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($c['Field'] ?? '');
            if ($f === 'document_type') $hasDocType = true;
            if ($f === 'document_number') $hasDocNumber = true;
            if ($f === 'reviewed_at') $hasReviewedAt = true;
            if ($f === 'reviewed_by') $hasReviewedBy = true;
        }
    } catch (Exception $e) { /* ignore */ }

    // Check users table columns used in JOIN
    $hasUserName = false; $hasUserEmail = true; // assume email exists
    try {
        $ucols = $pdo->query("SHOW COLUMNS FROM users");
        while ($c = $ucols->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($c['Field'] ?? '');
            if ($f === 'name') $hasUserName = true;
        }
    } catch (Exception $e) { /* ignore */ }

    // Get the KYC request and user details (only include columns that exist)
    $fields = ['k.user_id'];
    if ($hasUserEmail) { $fields[] = 'u.email'; }
    if ($hasUserName)  { $fields[] = 'u.name'; }
    if ($hasDocType)   { $fields[] = 'k.document_type'; }
    if ($hasDocNumber) { $fields[] = 'k.document_number'; }

    $sql = "SELECT " . implode(', ', $fields) . " FROM kyc_requests k JOIN users u ON k.user_id = u.id WHERE k.id=?";
    $getStmt = $pdo->prepare($sql);
    $getStmt->execute([$data['id']]);
    $kyc = $getStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$kyc) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "KYC submission not found"]);
        exit;
    }
    
    // Start transaction to ensure both tables are updated atomically
    $pdo->beginTransaction();
    
    // Update the KYC status in kyc_requests table (include columns only if they exist)
    $setParts = ["status='approved'"];
    $params = [];
    if ($hasReviewedAt) { $setParts[] = "reviewed_at=NOW()"; }
    if ($hasReviewedBy) { $setParts[] = "reviewed_by=?"; $params[] = isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1; }
    $setClause = implode(', ', $setParts);
    $stmt = $pdo->prepare("UPDATE kyc_requests SET $setClause WHERE id=?");
    $params[] = $data['id'];
    $stmt->execute($params);
    
    // CRITICAL: Also update users table to sync kyc_verified and, if available, kycStatus
    $hasKycVerifiedCol = false; $hasKycStatusCol = false; $hasIsVerifiedCol = false;
    try {
        $uc = $pdo->query("SHOW COLUMNS FROM users");
        while ($col = $uc->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($col['Field'] ?? '');
            if ($f === 'kyc_verified') $hasKycVerifiedCol = true;
            if ($f === 'kycstatus') $hasKycStatusCol = true;
            if ($f === 'is_verified') $hasIsVerifiedCol = true;
        }
    } catch (Exception $e) { /* ignore */ }

    $setParts = [];
    if ($hasKycVerifiedCol) { $setParts[] = "kyc_verified=1"; }
    if ($hasKycStatusCol)   { $setParts[] = "kycStatus='approved'"; }
    if ($hasIsVerifiedCol)  { $setParts[] = "is_verified=1"; }
    if (!empty($setParts)) {
        $syncStmt = $pdo->prepare("UPDATE users SET " . implode(', ', $setParts) . " WHERE id=?");
        $syncStmt->execute([$kyc['user_id']]);
    }
    
    // Log the action
    try {
        $logStmt = $pdo->prepare("
            INSERT INTO admin_logs (admin_id, action, details)
            VALUES (:admin_id, :action, :details)
        ");
        
        $logStmt->execute([
            ':admin_id' => isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1,
            ':action' => 'approve_kyc',
            ':details' => json_encode([
                'kyc_id' => $data['id'],
                'user_id' => $kyc['user_id'],
                'document_type' => $kyc['document_type'] ?? 'unknown'
            ])
        ]);
    } catch (Exception $logErr) {
        // Do not block approval if logging fails
        error_log('approve_kyc.php log error: ' . $logErr->getMessage());
    }
    
    // Send email notification to user (best-effort, avoid fatal if Mailer missing)
    try {
        $mailerPath = __DIR__ . '/includes/Mailer.php';
        if (file_exists($mailerPath)) {
            require_once $mailerPath;
            if (class_exists('Mailer')) {
                $mailer = new Mailer();
                $mailer->sendEmail(
                    $kyc['email'] ?? '',
                    'KYC Verification Approved',
                    "<h2>KYC Approved</h2><p>Dear " . ($kyc['name'] ?? 'User') . ",</p><p>Your KYC verification has been approved. You now have full access to all platform features.</p>",
                    "KYC Approved\n\nDear " . ($kyc['name'] ?? 'User') . ",\n\nYour KYC verification has been approved. You now have full access to all platform features."
                );
            }
        }
    } catch (Exception $emailError) {
        error_log("Failed to send KYC approval email: " . $emailError->getMessage());
        // Don't fail the approval if email fails
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode(["success" => true, "message" => "KYC submission approved successfully"]);
} catch (Throwable $e) {
    // Rollback transaction on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('approve_kyc.php error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
