<?php
/**
 * Installation Verification Script
 * Run this after installing the database to verify everything is set up correctly
 */

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

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

$results = [
    'timestamp' => date('Y-m-d H:i:s'),
    'status' => 'checking',
    'tables' => [],
    'directories' => [],
    'summary' => []
];

// List of required tables
$requiredTables = [
    'users',
    'admins', 
    'settings',
    'investment_plans',
    'transactions',
    'investments',
    'user_investments',
    'withdrawal_pins',
    'kyc_requests',
    'security_logs',
    'password_reset_tokens',
    'admin_logs',
    'payment_methods',
    'tickets',
    'notifications',
    'content',
    'logs',
    // Newly required tables in base install
    'loans',
    'admin_deposit_addresses',
    'user_address_requests',
    'user_pin_settings'
];

// Check database tables
try {
    $stmt = $pdo->query("SHOW TABLES");
    $existingTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    foreach ($requiredTables as $table) {
        $exists = in_array($table, $existingTables);
        $results['tables'][$table] = [
            'exists' => $exists,
            'status' => $exists ? 'OK' : 'MISSING',
            'required' => true
        ];
        
        // Get row count if table exists
        if ($exists) {
            try {
                $countStmt = $pdo->query("SELECT COUNT(*) FROM `$table`");
                $results['tables'][$table]['row_count'] = $countStmt->fetchColumn();
            } catch (Exception $e) {
                $results['tables'][$table]['row_count'] = 0;
            }
        }
    }
} catch (Exception $e) {
    $results['database_error'] = $e->getMessage();
}

// Check upload directories
$requiredDirs = [
    'uploads' => __DIR__ . '/../uploads/',
    'uploads/kyc' => __DIR__ . '/../uploads/kyc/',
    'uploads/profile' => __DIR__ . '/../uploads/profile/',
    'uploads/documents' => __DIR__ . '/../uploads/documents/'
];

foreach ($requiredDirs as $name => $path) {
    $exists = file_exists($path);
    $writable = is_writable($path);
    
    $results['directories'][$name] = [
        'path' => $path,
        'exists' => $exists,
        'writable' => $writable,
        'status' => ($exists && $writable) ? 'OK' : ($exists ? 'NOT_WRITABLE' : 'MISSING')
    ];
}

// Calculate summary
$missingTables = array_filter($results['tables'], function($t) { return !$t['exists']; });
$missingDirs = array_filter($results['directories'], function($d) { return $d['status'] !== 'OK'; });

$results['summary'] = [
    'total_tables_required' => count($requiredTables),
    'tables_found' => count($requiredTables) - count($missingTables),
    'tables_missing' => count($missingTables),
    'total_directories_required' => count($requiredDirs),
    'directories_ok' => count($requiredDirs) - count($missingDirs),
    'directories_issues' => count($missingDirs),
    'installation_complete' => (count($missingTables) === 0 && count($missingDirs) === 0)
];

$results['status'] = $results['summary']['installation_complete'] ? 'COMPLETE' : 'INCOMPLETE';

// Add recommendations
$results['recommendations'] = [];

if (count($missingTables) > 0) {
    $results['recommendations'][] = 'Run the installation script: mysql -u user -p database < install/tonsui_schema.sql';
}

if (count($missingDirs) > 0) {
    foreach ($missingDirs as $name => $dir) {
        if ($dir['status'] === 'MISSING') {
            $results['recommendations'][] = "Create directory: mkdir -p {$dir['path']}";
        } else if ($dir['status'] === 'NOT_WRITABLE') {
            $results['recommendations'][] = "Fix permissions: chmod 755 {$dir['path']}";
        }
    }
}

if ($results['summary']['installation_complete']) {
    $results['recommendations'][] = '✅ Installation complete! You can now use the application.';
    $results['next_steps'] = [
        '1. Create an admin user if not already done',
        '2. Configure your .env file',
        '3. Test the application',
        '4. Change default admin password'
    ];
}

echo json_encode($results, JSON_PRETTY_PRINT);
