<?php
/**
 * KYC Setup Diagnostic Tool
 * Run this to check if KYC system is properly configured
 */

header('Content-Type: application/json');

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/db.php';

$results = [
    'timestamp' => date('Y-m-d H:i:s'),
    'checks' => []
];

// Check 1: Database table exists
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'kyc_requests'");
    $tableExists = $stmt->rowCount() > 0;
    
    $results['checks'][] = [
        'name' => 'kyc_requests table',
        'status' => $tableExists ? 'OK' : 'MISSING',
        'message' => $tableExists ? 'Table exists' : 'Table does not exist - run create_kyc_table.sql'
    ];
    
    // Check 2: Table structure if it exists
    if ($tableExists) {
        $cols = $pdo->query("SHOW COLUMNS FROM kyc_requests");
        $columns = [];
        while ($col = $cols->fetch(PDO::FETCH_ASSOC)) {
            $columns[] = $col['Field'];
        }
        
        $requiredColumns = ['id', 'user_id', 'document_type', 'document_number', 'document_front', 'document_back', 'status', 'submitted_at'];
        $missingColumns = array_diff($requiredColumns, $columns);
        
        $results['checks'][] = [
            'name' => 'Table columns',
            'status' => empty($missingColumns) ? 'OK' : 'INCOMPLETE',
            'message' => empty($missingColumns) 
                ? 'All required columns present' 
                : 'Missing columns: ' . implode(', ', $missingColumns),
            'columns' => $columns
        ];
    }
} catch (Exception $e) {
    $results['checks'][] = [
        'name' => 'Database check',
        'status' => 'ERROR',
        'message' => $e->getMessage()
    ];
}

// Check 3: Upload directory exists and is writable
$uploadDir = __DIR__ . '/../uploads/kyc/';
$dirExists = file_exists($uploadDir);
$dirWritable = is_writable($uploadDir);

$results['checks'][] = [
    'name' => 'Upload directory',
    'path' => $uploadDir,
    'exists' => $dirExists,
    'writable' => $dirWritable,
    'status' => ($dirExists && $dirWritable) ? 'OK' : 'ISSUE',
    'message' => !$dirExists 
        ? 'Directory does not exist - will be created on first upload' 
        : (!$dirWritable ? 'Directory exists but is not writable - check permissions' : 'Directory ready')
];

// Check 4: File upload settings
$maxUpload = ini_get('upload_max_filesize');
$maxPost = ini_get('post_max_size');
$memoryLimit = ini_get('memory_limit');

$results['checks'][] = [
    'name' => 'PHP upload settings',
    'status' => 'INFO',
    'upload_max_filesize' => $maxUpload,
    'post_max_size' => $maxPost,
    'memory_limit' => $memoryLimit,
    'message' => 'Current PHP settings (should allow 5MB+ uploads)'
];

// Overall status
$hasErrors = false;
foreach ($results['checks'] as $check) {
    if (in_array($check['status'], ['ERROR', 'MISSING'])) {
        $hasErrors = true;
        break;
    }
}

$results['overall_status'] = $hasErrors ? 'ISSUES_FOUND' : 'OK';
$results['ready_for_kyc'] = !$hasErrors;

echo json_encode($results, JSON_PRETTY_PRINT);
