<?php
/**
 * ZLO Platform - Installation Script
 * 
 * This script helps with the initial installation and setup of ZLO Platform.
 * Run this script once after uploading files to your server.
 * 
 * IMPORTANT: Delete this file after installation is complete!
 */

declare(strict_types=1);

// Security check - only allow local access or with secret key
$secretKey = $_GET['key'] ?? '';
$expectedKey = $_ENV['INSTALL_KEY'] ?? 'zlo-install-2024';

if ($secretKey !== $expectedKey && !in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1', 'localhost'])) {
    http_response_code(403);
    die('Access denied. Please run from localhost or provide valid key.');
}

// Configuration
$requiredPhpVersion = '8.0.0';
$requiredExtensions = ['pdo', 'pdo_mysql', 'json', 'mbstring', 'gd', 'openssl'];
$writableDirs = ['uploads', 'logs'];

// Results
$results = [
    'php_version' => false,
    'extensions' => [],
    'directories' => [],
    'database' => false,
    'env_file' => false
];

// Check PHP version
$results['php_version'] = version_compare(PHP_VERSION, $requiredPhpVersion, '>=');

// Check extensions
foreach ($requiredExtensions as $ext) {
    $results['extensions'][$ext] = extension_loaded($ext);
}

// Check directories
foreach ($writableDirs as $dir) {
    $path = __DIR__ . '/' . $dir;
    $results['directories'][$dir] = [
        'exists' => is_dir($path),
        'writable' => is_writable($path)
    ];
}

// Check .env file
$results['env_file'] = file_exists(__DIR__ . '/.env');

// Check database connection
if ($results['extensions']['pdo'] && $results['extensions']['pdo_mysql']) {
    try {
        $config = require __DIR__ . '/api/config/config.php';
        $db = new PDO(
            "mysql:host={$config['database']['host']};port={$config['database']['port']}",
            $config['database']['user'],
            $config['database']['password']
        );
        $results['database'] = true;
    } catch (Exception $e) {
        $results['database_error'] = $e->getMessage();
    }
}

// Handle actions
$action = $_GET['action'] ?? 'check';
$message = '';

if ($action === 'install_db') {
    try {
        $config = require __DIR__ . '/api/config/config.php';
        
        // Create database if not exists
        $db = new PDO(
            "mysql:host={$config['database']['host']};port={$config['database']['port']}",
            $config['database']['user'],
            $config['database']['password']
        );
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $dbName = $config['database']['name'];
        $db->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $db->exec("USE `{$dbName}`");
        
        // Import schema
        $schema = file_get_contents(__DIR__ . '/database/schema.sql');
        $db->exec($schema);
        
        $message = 'Database installed successfully!';
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
    }
}

if ($action === 'create_env') {
    $envContent = "# ZLO Platform Environment Configuration
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-domain.com

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_NAME=zlo_platform
DB_USER=root
DB_PASSWORD=your_password

# JWT Configuration
JWT_SECRET=" . bin2hex(random_bytes(32)) . "
JWT_EXPIRATION=7200

# Email Configuration
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@zlotech.net
MAIL_FROM_NAME=\"ZLO Technologies\"

# Upload Configuration
UPLOAD_MAX_SIZE=10485760
UPLOAD_ALLOWED_TYPES=jpg,jpeg,png,gif,webp,svg,pdf,doc,docx

# Security
CSRF_TOKEN_NAME=csrf_token
SESSION_LIFETIME=7200

# reCAPTCHA (optional)
RECAPTCHA_SITE_KEY=
RECAPTCHA_SECRET_KEY=
";
    
    if (file_put_contents(__DIR__ . '/.env', $envContent)) {
        $message = '.env file created successfully!';
        $results['env_file'] = true;
    } else {
        $message = 'Failed to create .env file';
    }
}

// HTML Output
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZLO Platform - Installation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; padding: 2rem 0; }
        .install-card { max-width: 800px; margin: 0 auto; }
        .status-icon { font-size: 1.2rem; }
        .status-ok { color: #198754; }
        .status-error { color: #dc3545; }
        .logo { max-width: 150px; margin-bottom: 1rem; }
    </style>
</head>
<body>
    <div class="container">
        <div class="card install-card shadow">
            <div class="card-body p-4">
                <div class="text-center">
                    <h1 class="h3 mb-3">ZLO Platform Installation</h1>
                    <p class="text-muted">Complete SaaS Platform for ZLO Technologies</p>
                </div>
                
                <?php if ($message): ?>
                <div class="alert alert-info"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>
                
                <h5 class="mt-4">System Requirements</h5>
                <table class="table table-sm">
                    <tr>
                        <td>PHP Version (>= <?php echo $requiredPhpVersion; ?>)</td>
                        <td class="text-end">
                            <span class="status-icon <?php echo $results['php_version'] ? 'status-ok' : 'status-error'; ?>">
                                <?php echo $results['php_version'] ? '✓' : '✗'; ?>
                            </span>
                            <?php echo PHP_VERSION; ?>
                        </td>
                    </tr>
                    <?php foreach ($results['extensions'] as $ext => $loaded): ?>
                    <tr>
                        <td>Extension: <?php echo $ext; ?></td>
                        <td class="text-end">
                            <span class="status-icon <?php echo $loaded ? 'status-ok' : 'status-error'; ?>">
                                <?php echo $loaded ? '✓' : '✗'; ?>
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                
                <h5 class="mt-4">Directory Permissions</h5>
                <table class="table table-sm">
                    <?php foreach ($results['directories'] as $dir => $status): ?>
                    <tr>
                        <td><?php echo $dir; ?>/</td>
                        <td class="text-end">
                            <?php if ($status['exists'] && $status['writable']): ?>
                                <span class="status-icon status-ok">✓ Writable</span>
                            <?php elseif ($status['exists']): ?>
                                <span class="status-icon status-error">✗ Not writable</span>
                            <?php else: ?>
                                <span class="status-icon status-error">✗ Not found</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                
                <h5 class="mt-4">Configuration</h5>
                <table class="table table-sm">
                    <tr>
                        <td>.env file</td>
                        <td class="text-end">
                            <?php if ($results['env_file']): ?>
                                <span class="status-icon status-ok">✓ Found</span>
                            <?php else: ?>
                                <span class="status-icon status-error">✗ Not found</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td>Database Connection</td>
                        <td class="text-end">
                            <?php if ($results['database']): ?>
                                <span class="status-icon status-ok">✓ Connected</span>
                            <?php else: ?>
                                <span class="status-icon status-error">✗ Failed</span>
                                <?php if (!empty($results['database_error'])): ?>
                                    <small class="d-block text-danger"><?php echo htmlspecialchars($results['database_error']); ?></small>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
                
                <div class="mt-4 d-grid gap-2">
                    <?php if (!$results['env_file']): ?>
                    <a href="?action=create_env&key=<?php echo $secretKey; ?>" class="btn btn-primary">
                        Create .env File
                    </a>
                    <?php endif; ?>
                    
                    <?php if ($results['database']): ?>
                    <a href="?action=install_db&key=<?php echo $secretKey; ?>" class="btn btn-success">
                        Install Database
                    </a>
                    <?php endif; ?>
                    
                    <a href="?action=check&key=<?php echo $secretKey; ?>" class="btn btn-outline-secondary">
                        Refresh Check
                    </a>
                </div>
                
                <div class="alert alert-warning mt-4">
                    <strong>⚠️ Security Notice:</strong> Delete this file (install.php) after installation is complete!
                </div>
                
                <div class="text-center mt-4 text-muted">
                    <small>ZLO Platform v1.0.0 &copy; 2024 ZLO Technologies</small>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
