<?php
/**
 * ZexFaucet Pro Installation Checker
 * This script checks if the server meets the requirements for ZexFaucet Pro
 */

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Required PHP version
$required_php_version = '7.4.0';

// Required PHP extensions
$required_extensions = [
    'mysqli',
    'curl',
    'json',
    'mbstring',
    'openssl'
];

// Load database configuration from config file
$db_config = [];
$config_loaded = false;
$config_error = '';

try {
    // Define APPPATH if not already defined
    if (!defined('APPPATH')) {
        define('APPPATH', __DIR__ . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR);
    }
    
    // Check if Script config file exists
    if (!file_exists(APPPATH . 'Config/Script.php')) {
        throw new Exception('Database configuration file (app/Config/Script.php) not found.');
    }
    
    // Load the Script config file
    require_once APPPATH . 'Config/Script.php';
    $db_config = [
        'hostname' => \Config\Script::$hostname,
        'username' => \Config\Script::$username,
        'password' => \Config\Script::$password,
        'database' => \Config\Script::$database
    ];
    $config_loaded = true;
    
} catch (Exception $e) {
    $config_error = $e->getMessage();
    $config_loaded = false;
}

// Optional but recommended extensions
$recommended_extensions = [
    'intl',
    'xml',
    'simplexml',
    'dom'
];

// Check functions
function checkPhpVersion($required) {
    $current = PHP_VERSION;
    return version_compare($current, $required, '>=');
}

function checkExtension($extension) {
    return extension_loaded($extension);
}

function getPhpInfo() {
    return [
        'version' => PHP_VERSION,
        'sapi' => php_sapi_name(),
        'memory_limit' => ini_get('memory_limit'),
        'max_execution_time' => ini_get('max_execution_time'),
        'upload_max_filesize' => ini_get('upload_max_filesize'),
        'post_max_size' => ini_get('post_max_size')
    ];
}

function checkWritableDirectories() {
    $directories = [
        'writable/',
        'writable/cache/',
        'writable/logs/',
        'writable/session/',
        'writable/uploads/'
    ];
    
    $results = [];
    foreach ($directories as $dir) {
        $results[$dir] = [
            'exists' => is_dir($dir),
            'writable' => is_writable($dir)
        ];
    }
    
    return $results;
}

function testDatabaseConnection($config) {
    try {
        $connection = new mysqli($config['hostname'], $config['username'], $config['password']);
        if ($connection->connect_error) {
            return ['success' => false, 'error' => $connection->connect_error];
        }
        $connection->close();
        return ['success' => true];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function createDatabase($config) {
    try {
        $connection = new mysqli($config['hostname'], $config['username'], $config['password']);
        if ($connection->connect_error) {
            return ['success' => false, 'error' => $connection->connect_error];
        }
        
        $sql = "CREATE DATABASE IF NOT EXISTS `{$config['database']}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci";
        if ($connection->query($sql) === TRUE) {
            $connection->close();
            return ['success' => true];
        } else {
            $error = $connection->error;
            $connection->close();
            return ['success' => false, 'error' => $error];
        }
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function createTables($config) {
    try {
        $connection = new mysqli($config['hostname'], $config['username'], $config['password'], $config['database']);
        if ($connection->connect_error) {
            return ['success' => false, 'error' => $connection->connect_error];
        }
        
        // SQL for creating tables
        $sql = "
        -- Table structure for table `faucet_history`
        CREATE TABLE IF NOT EXISTS `faucet_history` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `user_id` int(255) NOT NULL,
          `reward` decimal(18,10) NOT NULL,
          `ip` varchar(255) NOT NULL,
          `time_stamp` timestamp NULL DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

        -- Table structure for table `link_history`
        CREATE TABLE IF NOT EXISTS `link_history` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `link_id` int(255) NOT NULL,
          `user_id` int(255) NOT NULL,
          `ip` varchar(255) NOT NULL,
          `url` varchar(255) NOT NULL,
          `reward` decimal(18,10) NOT NULL,
          `hash` varchar(255) NOT NULL,
          `time_stamp` timestamp NULL DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

        -- Table structure for table `payouts`
        CREATE TABLE IF NOT EXISTS `payouts` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `user_id` int(255) NOT NULL,
          `address` varchar(255) NOT NULL,
          `currency` varchar(255) NOT NULL,
          `type` varchar(255) NOT NULL,
          `amount` decimal(18,10) NOT NULL,
          `amount_currency` decimal(18,10) NOT NULL,
          `time_stamp` timestamp NOT NULL DEFAULT current_timestamp(),
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

        -- Table structure for table `settings`
        CREATE TABLE IF NOT EXISTS `settings` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `value` longtext NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

        -- Table structure for table `shortlink`
        CREATE TABLE IF NOT EXISTS `shortlink` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `name` varchar(255) NOT NULL,
          `reward` decimal(18,10) NOT NULL,
          `view` int(255) NOT NULL,
          `api_key` varchar(255) NOT NULL,
          `priority` int(255) NOT NULL DEFAULT 0,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

        -- Table structure for table `users`
        CREATE TABLE IF NOT EXISTS `users` (
          `id` int(255) NOT NULL AUTO_INCREMENT,
          `email` varchar(255) NOT NULL,
          `ref` varchar(255) DEFAULT NULL,
          `ip` varchar(255) DEFAULT NULL,
          `currency` varchar(255) DEFAULT NULL,
          `last_active` timestamp NULL DEFAULT NULL,
          `registered_date` timestamp NULL DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
        ";
        
        if ($connection->multi_query($sql)) {
            // Wait for all queries to complete
            while ($connection->next_result()) {
                if ($result = $connection->store_result()) {
                    $result->free();
                }
            }
        }
        
        $connection->close();
        return ['success' => true];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function insertDefaultSettings($config) {
    try {
        $connection = new mysqli($config['hostname'], $config['username'], $config['password'], $config['database']);
        if ($connection->connect_error) {
            return ['success' => false, 'error' => $connection->connect_error];
        }
        
        // Check if settings already exist
        $result = $connection->query("SELECT COUNT(*) as count FROM settings");
        $row = $result->fetch_assoc();
        
        if ($row['count'] > 0) {
            $connection->close();
            return ['success' => true, 'message' => 'Settings already exist'];
        }
        
        // Insert default settings
        $settings = [
            ['site_name', 'ZexFaucet Pro Script'],
            ['maintenance', 'off'],
            ['faucet_status', 'off'],
            ['shortlink_status', 'off'],
            ['ref_bonus', '10'],
            ['faucet_reward', '0.00'],
            ['faucet_timer', '3'],
            ['faucet_limit', '0'],
            ['site_desc', ''],
            ['vpn_service', ''],
            ['vpn_check', ''],
            ['proxycheck_key', ''],
            ['iphub_key', ''],
            ['sl_timer', ''],
            ['captcha', ''],
            ['captcha_key', '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'],
            ['captcha_secret', '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'],
            ['microwallet', 'zexpay'],
            ['faucetpay_key', ''],
            ['zexpay_key', ''],
            ['currency', '[]'],
            ['home_top_ad', ''],
            ['home_bottom_ad', ''],
            ['dashboard_top_ad', ''],
            ['dashboard_bottom_ad', ''],
            ['faucet_top_ad', ''],
            ['faucet_bottom_ad', ''],
            ['faucet_square_ad', ''],
            ['sl_top_ad', ''],
            ['sl_bottom_ad', ''],
            ['ref_top_ad', ''],
            ['ref_bottom_ad', ''],
            ['admin_user', 'admin'],
            ['admin_pass', password_hash('admin', PASSWORD_DEFAULT)]
        ];
        
        $stmt = $connection->prepare("INSERT INTO settings (name, value) VALUES (?, ?)");
        foreach ($settings as $setting) {
            $stmt->bind_param("ss", $setting[0], $setting[1]);
            $stmt->execute();
        }
        
        $stmt->close();
        $connection->close();
        return ['success' => true];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// Perform checks
$php_version_ok = checkPhpVersion($required_php_version);
$php_info = getPhpInfo();
$writable_dirs = checkWritableDirectories();

$missing_extensions = [];
$recommended_missing = [];

foreach ($required_extensions as $ext) {
    if (!checkExtension($ext)) {
        $missing_extensions[] = $ext;
    }
}

foreach ($recommended_extensions as $ext) {
    if (!checkExtension($ext)) {
        $recommended_missing[] = $ext;
    }
}

// Database checks
$db_connection_ok = false;
$db_created = false;
$tables_created = false;
$settings_inserted = false;
$db_errors = [];

// Only proceed with database checks if config is loaded successfully
if ($config_loaded) {
    // Test database connection
    $db_test = testDatabaseConnection($db_config);
    if ($db_test['success']) {
        $db_connection_ok = true;
        
        // Create database if it doesn't exist
        $db_create = createDatabase($db_config);
        if ($db_create['success']) {
            $db_created = true;
            
            // Create tables
            $tables_result = createTables($db_config);
            if ($tables_result['success']) {
                $tables_created = true;
                
                // Insert default settings
                $settings_result = insertDefaultSettings($db_config);
                if ($settings_result['success']) {
                    $settings_inserted = true;
                } else {
                    $db_errors[] = 'Settings insertion failed: ' . $settings_result['error'];
                }
            } else {
                $db_errors[] = 'Table creation failed: ' . $tables_result['error'];
            }
        } else {
            $db_errors[] = 'Database creation failed: ' . $db_create['error'];
        }
    } else {
        $db_errors[] = 'Database connection failed: ' . $db_test['error'];
    }
} else {
    $db_errors[] = $config_error;
}

$all_checks_passed = $php_version_ok && empty($missing_extensions) && $config_loaded && $db_connection_ok && $db_created && $tables_created && $settings_inserted;

if($all_checks_passed){
    header('Location: admin/login');
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZexFaucet Pro - Installation Check</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }
        
        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .content {
            padding: 40px;
        }
        
        .check-section {
            margin-bottom: 30px;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #e0e0e0;
        }
        
        .check-section.success {
            background: #f0f9ff;
            border-left-color: #10b981;
        }
        
        .check-section.error {
            background: #fef2f2;
            border-left-color: #ef4444;
        }
        
        .check-section.warning {
            background: #fffbeb;
            border-left-color: #f59e0b;
        }
        
        .check-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        
        .check-icon {
            margin-right: 10px;
            font-size: 1.5rem;
        }
        
        .check-list {
            list-style: none;
        }
        
        .check-list li {
            padding: 8px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .status.ok {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status.error {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status.warning {
            background: #fef3c7;
            color: #92400e;
        }
        
        .php-info {
            background: #f8fafc;
            padding: 15px;
            border-radius: 6px;
            margin-top: 10px;
        }
        
        .php-info table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .php-info td {
            padding: 8px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .php-info td:first-child {
            font-weight: 500;
            color: #4a5568;
        }
        
        .action-buttons {
            text-align: center;
            margin-top: 30px;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 30px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 500;
            margin: 0 10px;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #e2e8f0;
            color: #4a5568;
        }
        
        .btn-secondary:hover {
            background: #cbd5e0;
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .footer {
            background: #f8fafc;
            padding: 20px;
            text-align: center;
            color: #6b7280;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 ZexFaucet Pro</h1>
            <p>Installation Requirements Check</p>
        </div>
        
        <div class="content">
            <!-- PHP Version Check -->
            <div class="check-section <?= $php_version_ok ? 'success' : 'error' ?>">
                <div class="check-title">
                    <span class="check-icon"><?= $php_version_ok ? '✅' : '❌' ?></span>
                    PHP Version Check
                </div>
                <p>
                    <?php if ($php_version_ok): ?>
                        Great! Your PHP version (<?= $php_info['version'] ?>) meets the requirement (<?= $required_php_version ?>+).
                    <?php else: ?>
                        <strong>Error:</strong> Your PHP version (<?= $php_info['version'] ?>) is too old. 
                        ZexFaucet Pro requires PHP <?= $required_php_version ?> or higher.
                    <?php endif; ?>
                </p>
                
                <div class="php-info">
                    <table>
                        <tr>
                            <td>Current Version:</td>
                            <td><?= $php_info['version'] ?></td>
                        </tr>
                        <tr>
                            <td>Required Version:</td>
                            <td><?= $required_php_version ?>+</td>
                        </tr>
                        <tr>
                            <td>SAPI:</td>
                            <td><?= $php_info['sapi'] ?></td>
                        </tr>
                        <tr>
                            <td>Memory Limit:</td>
                            <td><?= $php_info['memory_limit'] ?></td>
                        </tr>
                        <tr>
                            <td>Max Execution Time:</td>
                            <td><?= $php_info['max_execution_time'] ?>s</td>
                        </tr>
                    </table>
                </div>
            </div>
            
            <!-- Required Extensions Check -->
            <div class="check-section <?= empty($missing_extensions) ? 'success' : 'error' ?>">
                <div class="check-title">
                    <span class="check-icon"><?= empty($missing_extensions) ? '✅' : '❌' ?></span>
                    Required PHP Extensions
                </div>
                <ul class="check-list">
                    <?php foreach ($required_extensions as $ext): ?>
                        <li>
                            <span><?= $ext ?></span>
                            <span class="status <?= checkExtension($ext) ? 'ok' : 'error' ?>">
                                <?= checkExtension($ext) ? 'Installed' : 'Missing' ?>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <?php if (!empty($missing_extensions)): ?>
                    <p style="margin-top: 15px; color: #dc2626;">
                        <strong>Missing extensions:</strong> <?= implode(', ', $missing_extensions) ?>
                    </p>
                <?php endif; ?>
            </div>
            
            <!-- Recommended Extensions Check -->
            <?php if (!empty($recommended_missing)): ?>
            <div class="check-section warning">
                <div class="check-title">
                    <span class="check-icon">⚠️</span>
                    Recommended PHP Extensions
                </div>
                <ul class="check-list">
                    <?php foreach ($recommended_extensions as $ext): ?>
                        <li>
                            <span><?= $ext ?></span>
                            <span class="status <?= checkExtension($ext) ? 'ok' : 'warning' ?>">
                                <?= checkExtension($ext) ? 'Installed' : 'Recommended' ?>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
                <p style="margin-top: 15px; color: #d97706;">
                    These extensions are recommended for better performance and functionality.
                </p>
            </div>
            <?php endif; ?>
            
            <!-- Directory Permissions Check -->
            <div class="check-section <?= array_reduce($writable_dirs, function($carry, $dir) { return $carry && $dir['exists'] && $dir['writable']; }, true) ? 'success' : 'error' ?>">
                <div class="check-title">
                    <span class="check-icon"><?= array_reduce($writable_dirs, function($carry, $dir) { return $carry && $dir['exists'] && $dir['writable']; }, true) ? '✅' : '❌' ?></span>
                    Directory Permissions
                </div>
                <ul class="check-list">
                    <?php foreach ($writable_dirs as $dir => $status): ?>
                        <li>
                            <span><?= $dir ?></span>
                            <span class="status <?= $status['exists'] && $status['writable'] ? 'ok' : 'error' ?>">
                                <?php if (!$status['exists']): ?>
                                    Missing
                                <?php elseif (!$status['writable']): ?>
                                    Not Writable
                                <?php else: ?>
                                    OK
                                <?php endif; ?>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            
            <!-- Database Installation Check -->
            <div class="check-section <?= $db_connection_ok && $db_created && $tables_created && $settings_inserted ? 'success' : 'error' ?>">
                <div class="check-title">
                    <span class="check-icon"><?= $db_connection_ok && $db_created && $tables_created && $settings_inserted ? '✅' : '❌' ?></span>
                    Database Installation
                </div>
                
                <!-- Database Configuration Details -->
                <div class="php-info" style="margin-bottom: 20px;">
                    <h4 style="margin-bottom: 10px; color: #4a5568;">Database Configuration:</h4>
                    <?php if ($config_loaded): ?>
                        <table>
                            <tr>
                                <td>Config Source:</td>
                                <td>Script.php Config File</td>
                            </tr>
                            <tr>
                                <td>Hostname:</td>
                                <td><?= htmlspecialchars($db_config['hostname']) ?></td>
                            </tr>
                            <tr>
                                <td>Username:</td>
                                <td><?= htmlspecialchars($db_config['username']) ?></td>
                            </tr>
                            <tr>
                                <td>Password:</td>
                                <td><?= !empty($db_config['password']) ? '***' . substr($db_config['password'], -2) : '(Empty)' ?></td>
                            </tr>
                            <tr>
                                <td>Database:</td>
                                <td><?= htmlspecialchars($db_config['database']) ?></td>
                            </tr>
                        </table>
                    <?php else: ?>
                        <div style="padding: 15px; background: #fef2f2; border-radius: 6px; border-left: 4px solid #ef4444;">
                            <strong style="color: #dc2626;">Configuration Error:</strong>
                            <p style="margin: 5px 0 0 0; color: #991b1b;"><?= htmlspecialchars($config_error) ?></p>
                        </div>
                    <?php endif; ?>
                </div>
                <ul class="check-list">
                    <li>
                        <span>Database Connection</span>
                        <span class="status <?= $db_connection_ok ? 'ok' : 'error' ?>">
                            <?= $db_connection_ok ? 'Connected' : 'Failed' ?>
                        </span>
                    </li>
                    <li>
                        <span>Database Creation</span>
                        <span class="status <?= $db_created ? 'ok' : 'error' ?>">
                            <?= $db_created ? 'Created' : 'Failed' ?>
                        </span>
                    </li>
                    <li>
                        <span>Tables Creation</span>
                        <span class="status <?= $tables_created ? 'ok' : 'error' ?>">
                            <?= $tables_created ? 'Created' : 'Failed' ?>
                        </span>
                    </li>
                    <li>
                        <span>Default Settings</span>
                        <span class="status <?= $settings_inserted ? 'ok' : 'error' ?>">
                            <?= $settings_inserted ? 'Inserted' : 'Failed' ?>
                        </span>
                    </li>
                </ul>
                <?php if (!empty($db_errors)): ?>
                    <div style="margin-top: 15px; padding: 10px; background: #fef2f2; border-radius: 4px; border-left: 4px solid #ef4444;">
                        <strong style="color: #dc2626;">Database Errors:</strong>
                        <ul style="margin: 5px 0 0 20px; color: #991b1b;">
                            <?php foreach ($db_errors as $error): ?>
                                <li><?= htmlspecialchars($error) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
            </div>
            
             <!-- Action Buttons -->
             <div class="action-buttons">
                 <?php if ($all_checks_passed): ?>
                     <a href="javascript:location.reload()" class="btn btn-secondary">Refresh Check</a>
                     <a href="admin/login" class="btn btn-primary">Proceed to Admin Login</a>
                 <?php else: ?>
                     <a href="javascript:location.reload()" class="btn btn-secondary">Refresh Check</a>
                     <a href="#" class="btn btn-primary" disabled>Fix Requirements First</a>
                 <?php endif; ?>
             </div>
        </div>
        
        <div class="footer">
            <p>ZexFaucet Pro Installation Checker | Make sure to delete this file after installation for security reasons.</p>
        </div>
    </div>
</body>
</html>
