<?php
/**
 * reject_kyc.php: Handles admin rejection 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;
}

// 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 {
    // Get the KYC request and user details
    $getStmt = $pdo->prepare("
        SELECT k.user_id, k.document_type, k.document_number, u.email, u.name 
        FROM kyc_requests k
        JOIN users u ON k.user_id = u.id
        WHERE k.id=?
    ");
    $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;
    }
    
    // Get rejection reason if provided
    $rejection_reason = $data['reason'] ?? 'Your KYC documents did not meet our verification requirements. Please resubmit with clear, valid documents.';
    
    // Start transaction to ensure both tables are updated atomically
    $pdo->beginTransaction();
    
    // Update the KYC status in kyc_requests table with admin notes
    $stmt = $pdo->prepare("UPDATE kyc_requests SET status='rejected', admin_notes=?, reviewed_at=NOW(), reviewed_by=? WHERE id=?");
    $stmt->execute([$rejection_reason, isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1, $data['id']]);
    
    // CRITICAL: Also update users table to sync KYC flags (schema-aware)
    $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=0"; }
    if ($hasKycStatusCol)   { $setParts[] = "kycStatus='rejected'"; }
    if ($hasIsVerifiedCol)  { $setParts[] = "is_verified=0"; }
    if (!empty($setParts)) {
        $syncStmt = $pdo->prepare("UPDATE users SET " . implode(', ', $setParts) . " WHERE id=?");
        $syncStmt->execute([$kyc['user_id']]);
    }
    
    // Log the action
    $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' => 'reject_kyc',
        ':details' => json_encode([
            'kyc_id' => $data['id'],
            'user_id' => $kyc['user_id'],
            'document_type' => $kyc['document_type'] ?? 'unknown',
            'reason' => $rejection_reason
        ])
    ]);
    
    // Send email notification to user
    try {
        require_once __DIR__ . '/includes/Mailer.php';
        $mailer = new Mailer();
        $mailer->sendEmail(
            $kyc['email'],
            'KYC Verification Rejected',
            "<h2>KYC Rejected</h2><p>Dear {$kyc['name']},</p><p>Your KYC verification has been rejected.</p><p><strong>Reason:</strong> {$rejection_reason}</p><p>Please review the requirements and submit again.</p>",
            "KYC Rejected\n\nDear {$kyc['name']},\n\nYour KYC verification has been rejected.\n\nReason: {$rejection_reason}\n\nPlease review the requirements and submit again."
        );
    } catch (Exception $emailError) {
        error_log("Failed to send KYC rejection email: " . $emailError->getMessage());
        // Don't fail the rejection if email fails
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode(["success" => true, "message" => "KYC submission rejected successfully"]);
} catch (Exception $e) {
    // Rollback transaction on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
