<?php
// ==========================================
// INSTALLER BACKEND API
// ==========================================

$basePath = dirname(__DIR__); 
$envFile = $basePath . '/.env';
$envExampleFile = $basePath . '/.env.example';
$lockFile = __DIR__ . '/install.lock';

// --- SECURITY CHECK ---
if (file_exists($envFile) && file_exists($lockFile)) {
    if (isset($_GET['installer_api'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Application is already installed.']);
        exit;
    }
}

$action = $_GET['installer_api'] ?? null;

if ($action) {
    header('Content-Type: application/json');

    try {
        switch ($action) {
            case 'requirements':
                $requirements = [
                    'PHP >= 8.2' => version_compare(PHP_VERSION, '8.2.0', '>='),
                    'BCMath Extension' => extension_loaded('bcmath'), 'Ctype Extension' => extension_loaded('ctype'),
                    'Fileinfo Extension' => extension_loaded('fileinfo'), 'JSON Extension' => extension_loaded('json'),
                    'Mbstring Extension' => extension_loaded('mbstring'), 'OpenSSL Extension' => extension_loaded('openssl'),
                    'PDO Extension' => defined('PDO::ATTR_DRIVER_NAME'), 'Tokenizer Extension' => extension_loaded('tokenizer'),
                    'XML Extension' => extension_loaded('xml'), 'cURL Extension' => extension_loaded('curl'),
                ];
                $passed = !in_array(false, $requirements, true);
                echo json_encode(['success' => true, 'data' => $requirements, 'passed' => $passed]);
                break;

            case 'permissions':
                $permissions = [
                    'storage/framework/' => is_writable($basePath . '/storage/framework/'),
                    'storage/logs/' => is_writable($basePath . '/storage/logs/'),
                    'bootstrap/cache/' => is_writable($basePath . '/bootstrap/cache/'),
                    'Root Directory (.env)' => is_writable($basePath),
                ];
                $passed = !in_array(false, $permissions, true);
                echo json_encode(['success' => true, 'data' => $permissions, 'passed' => $passed]);
                break;

            case 'database':
                $input = json_decode(file_get_contents('php://input'), true);
                $dsn = "mysql:host={$input['db_host']};port={$input['db_port']};dbname={$input['db_name']}";
                $pdo = new PDO($dsn, $input['db_user'], $input['db_pass']);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                echo json_encode(['success' => true]);
                break;

            case 'install':
                $input = json_decode(file_get_contents('php://input'), true);
                $runSeeders = $input['run_seeders'] ?? true;
                $warnings = []; 

                if (!file_exists($envExampleFile)) throw new Exception('.env.example is missing.');
                $envContent = file_get_contents($envExampleFile);
                $appKey = 'base64:' . base64_encode(random_bytes(32));
                $appUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];

                $setEnv = function($content, $key, $value) {
                    $pattern = "/^" . preg_quote($key, '/') . "=.*/m";
                    $line = $key . '=' . '"' . $value . '"';
                    if (preg_match($pattern, $content)) {
                        return preg_replace($pattern, $line, $content);
                    }
                    return $content . PHP_EOL . $line;
                };

                $envContent = $setEnv($envContent, 'APP_KEY', $appKey);
                $envContent = $setEnv($envContent, 'APP_URL', $appUrl);
                $envContent = $setEnv($envContent, 'DB_CONNECTION', 'mysql');
                $envContent = $setEnv($envContent, 'DB_HOST', $input['db_host']);
                $envContent = $setEnv($envContent, 'DB_PORT', $input['db_port']);
                $envContent = $setEnv($envContent, 'DB_DATABASE', $input['db_name']);
                $envContent = $setEnv($envContent, 'DB_USERNAME', $input['db_user']);
                $envContent = $setEnv($envContent, 'DB_PASSWORD', $input['db_pass']);
                file_put_contents($envFile, $envContent);

                $_ENV['DB_CONNECTION'] = 'mysql'; $_ENV['DB_HOST'] = $input['db_host']; $_ENV['DB_PORT'] = $input['db_port'];
                $_ENV['DB_DATABASE'] = $input['db_name']; $_ENV['DB_USERNAME'] = $input['db_user']; $_ENV['DB_PASSWORD'] = $input['db_pass'];

                require $basePath . '/vendor/autoload.php';
                $app = require_once $basePath . '/bootstrap/app.php';
                $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
                $kernel->bootstrap();
                
                \Illuminate\Support\Facades\Artisan::call('config:clear');
                \Illuminate\Support\Facades\Artisan::call('migrate:fresh', ['--force' => true]);

                if ($runSeeders) {
                    \Illuminate\Support\Facades\Artisan::call('db:seed', ['--force' => true]);
                } else {
                    \App\Models\User::create([
                        'name' => $input['admin_name'], 'username' => $input['admin_username'],
                        'email' => $input['admin_email'], 'password' => \Illuminate\Support\Facades\Hash::make($input['admin_password']),
                        'role' => 'admin', 'email_verified_at' => now(),
                    ]);
                    \Illuminate\Support\Facades\Artisan::call('db:seed', ['--class' => 'LanguageSeeder', '--force' => true]);
                    \Illuminate\Support\Facades\Artisan::call('db:seed', ['--class' => 'SeoSettingsSeeder', '--force' => true]);
                }

                try {
                    $linkPath = $basePath . '/public/storage';
                    if (is_link($linkPath)) {
                        @unlink($linkPath);
                    } elseif (is_dir($linkPath)) {
                        throw new Exception("A directory named 'storage' already exists in 'public'. Please remove it manually.");
                    } elseif (file_exists($linkPath)) {
                        @unlink($linkPath);
                    }
                    \Illuminate\Support\Facades\Artisan::call('storage:link');
                } catch (Exception $e) {
                    $warnings[] = "Could not automatically create the storage symlink due to an error: '{$e->getMessage()}'. You must run 'php artisan storage:link' manually from your server's command line to make images visible.";
                }
                
                file_put_contents($lockFile, json_encode(['installed_at' => date('Y-m-d H:i:s')]));

                echo json_encode(['success' => true, 'warnings' => $warnings]);
                break;
            
            default:
                throw new Exception('Invalid API action.');
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => get_class($e) . ': ' . $e->getMessage()]);
    }
    exit;
}