<?php
/**
 * Update KYC Status Endpoint
 * 
 * Updates the status of a KYC verification request
 * 
 * Required POST Parameters:
 * - id: KYC request ID
 * - status: New status (pending/approved/rejected)
 * - admin_notes: Optional notes from admin
 * 
 * Required Headers:
 * - Content-Type: application/json
 * 
 * Response:
 * - success: boolean
 * - message: string (status message or error)
 */

// Include configuration and authentication
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/includes/Database.php';

// Set content type to JSON
header('Content-Type: application/json');

// Initialize response array
$response = [
    'success' => false,
    'message' => ''
];

// Verify request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Method not allowed';
    echo json_encode($response);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
if (empty($input['id'])) {
    http_response_code(400);
    $response['message'] = 'KYC request ID is required';
    echo json_encode($response);
    exit;
}

if (empty($input['status']) || !in_array($input['status'], ['pending', 'approved', 'rejected'])) {
    http_response_code(400);
    $response['message'] = 'Invalid status. Must be one of: pending, approved, rejected';
    echo json_encode($response);
    exit;
}

try {
    // Verify admin authentication
    $auth = new Auth();
    if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
        http_response_code(403);
        $response['message'] = 'Unauthorized: Admin access required';
        echo json_encode($response);
        exit;
    }
    
    // Get database connection
    $db = Database::getInstance()->getConnection();
    
    // Get admin user ID
    $adminId = $auth->getUserId();
    
    // Prepare update data
    $updateData = [
        'id' => $input['id'],
        'status' => $input['status'],
        'admin_notes' => $input['admin_notes'] ?? '',
        'admin_id' => $adminId,
        'updated_at' => date('Y-m-d H:i:s')
    ];
    
    // Detect KYC table (schema-aware)
    $kycTable = 'kyc_verifications';
    try {
        $t = $db->query("SHOW TABLES LIKE 'kyc_verifications'");
        if (!$t || $t->rowCount() === 0) {
            $t2 = $db->query("SHOW TABLES LIKE 'kyc_requests'");
            if ($t2 && $t2->rowCount() > 0) { $kycTable = 'kyc_requests'; }
        }
    } catch (Exception $e) { /* ignore */ }

    // Update KYC request with appropriate columns
    if ($kycTable === 'kyc_verifications') {
        $stmt = $db->prepare("UPDATE kyc_verifications 
            SET status = :status, 
                admin_notes = :admin_notes, 
                admin_id = :admin_id,
                updated_at = :updated_at
            WHERE id = :id");
        $success = $stmt->execute($updateData);
    } else {
        // kyc_requests table: uses reviewed_by and reviewed_at
        $stmt = $db->prepare("UPDATE kyc_requests 
            SET status = :status, 
                admin_notes = :admin_notes, 
                reviewed_by = :admin_id,
                reviewed_at = :updated_at
            WHERE id = :id");
        $success = $stmt->execute($updateData);
    }
    
    if ($success && $stmt->rowCount() > 0) {
        // If approved, update user's KYC status
        if ($input['status'] === 'approved') {
            updateUserKycStatus($db, $input['id']);
        }
        
        $response['success'] = true;
        $response['message'] = 'KYC status updated successfully';
    } else {
        $response['message'] = 'No changes made or KYC request not found';
    }
    
} catch (PDOException $e) {
    http_response_code(500);
    $response['message'] = 'Database error: ' . $e->getMessage();
    
} catch (Exception $e) {
    http_response_code(500);
    $response['message'] = 'Server error: ' . $e->getMessage();
}

// Return JSON response
echo json_encode($response);

/**
 * Update user's KYC status after approval
 */
function updateUserKycStatus($db, $kycId) {
    // Determine source table for KYC requests
    $kycTable = 'kyc_verifications';
    try {
        $t = $db->query("SHOW TABLES LIKE 'kyc_verifications'");
        if (!$t || $t->rowCount() === 0) {
            $t2 = $db->query("SHOW TABLES LIKE 'kyc_requests'");
            if ($t2 && $t2->rowCount() > 0) { $kycTable = 'kyc_requests'; }
        }
    } catch (Exception $e) { /* ignore */ }

    // Get user ID from KYC request
    $stmt = $db->prepare("SELECT user_id FROM {$kycTable} WHERE id = ?");
    $stmt->execute([$kycId]);
    $kyc = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($kyc && !empty($kyc['user_id'])) {
        // Discover available KYC flags on users table
        $hasKycVerified = false; $hasKycStatus = false; $hasIsVerified = false;
        try {
            $cols = $db->query("SHOW COLUMNS FROM users");
            while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
                $f = strtolower($c['Field'] ?? '');
                if ($f === 'kyc_verified') $hasKycVerified = true;
                if ($f === 'kycstatus') $hasKycStatus = true; // compare lowercased
                if ($f === 'is_verified') $hasIsVerified = true;
            }
        } catch (Exception $e) { /* ignore */ }

        $setParts = [];
        if ($hasKycStatus)   { $setParts[] = "kycStatus='approved'"; }
        if ($hasKycVerified) { $setParts[] = "kyc_verified=1"; }
        if ($hasIsVerified)  { $setParts[] = "is_verified=1"; }

        if (!empty($setParts)) {
            $sql = "UPDATE users SET " . implode(', ', $setParts) . ", updated_at = NOW() WHERE id = ?";
            $updateUser = $db->prepare($sql);
            $updateUser->execute([$kyc['user_id']]);
        }
    }
}

// DB connection handled by Database singleton
