<?php
// Installer API Endpoint
header('Content-Type: application/json');
error_reporting(0);

// Bulletproof dynamic Root Directory resolution
$currentDir = __DIR__;
$parentDir = dirname($currentDir);
$rootDir = (basename($parentDir) === 'public') ? dirname($parentDir) : $parentDir;
define('ROOT_DIR', $rootDir);

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

// SECURITY: If .env exists, lock out the API.
if (file_exists(ROOT_DIR . '/.env')) {
    echo json_encode(['success' => false, 'message' => 'App is already installed.']);
    exit;
}

$action = $_POST['action'];

if ($action === 'install_db') {
    $host = $_POST['db_host'] ?? '';
    $user = $_POST['db_user'] ?? '';
    $pass = $_POST['db_pass'] ?? '';
    $name = $_POST['db_name'] ?? '';

    try {
        // 1. Test Connection
        $pdo = new PDO("mysql:host=$host", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        
        // 2. Create DB if not exists & Use it
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name`");
        $pdo->exec("USE `$name`");

        // 3. Import Base Schema
        $schemaPath = __DIR__ . '/schema.sql';
        if (!file_exists($schemaPath)) {
            throw new Exception("Core schema.sql file is missing from the installer directory.");
        }
        $sql = file_get_contents($schemaPath);
        $pdo->exec($sql);

        // 4. Clean out dummy data
        $pdo->exec("SET FOREIGN_KEY_CHECKS=0; 
                    TRUNCATE TABLE email_queue;
                    TRUNCATE TABLE jobcards;
                    TRUNCATE TABLE jobcard_materials;
                    TRUNCATE TABLE partners;
                    TRUNCATE TABLE password_resets;
                    TRUNCATE TABLE support_tickets;
                    TRUNCATE TABLE system_logs;
                    TRUNCATE TABLE users;
                    TRUNCATE TABLE user_backup_codes;
                    SET FOREIGN_KEY_CHECKS=1;");

        // 5. Force the base database version to 0
        $pdo->exec("UPDATE settings SET setting_value = '0' WHERE setting_key = 'db_version'");

        // 6. Run Migrations (like OTA update)
        $migrationsDir = ROOT_DIR . '/migrations';
        $highestVersion = 0;
        if (is_dir($migrationsDir)) {
            $migrationFiles = glob($migrationsDir . '/*.sql');
            if ($migrationFiles) {
                sort($migrationFiles);
                foreach ($migrationFiles as $file) {
                    $pdo->exec(file_get_contents($file));
                    preg_match('/^(\d+)_/', basename($file), $matches);
                    if (isset($matches[1])) {
                        $highestVersion = (int)$matches[1];
                        $pdo->exec("UPDATE settings SET setting_value = '$highestVersion' WHERE setting_key = 'db_version'");
                    }
                }
            }
        }

        // 7. Generate the .env file string
        $envData = "DB_HOST={$host}\nDB_USER={$user}\nDB_PASS={$pass}\nDB_NAME={$name}\n";
        $envData .= "APP_URL=" . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}\n";
        $envData .= "APP_NAME=\"Jobcard Manager Pro\"\n";
        $envData .= "APP_TIMEZONE=\"Africa/Johannesburg\"\n";
        $envData .= "APP_CURRENCY=\"ZAR\"\n";
        $envData .= "APP_KEY=" . bin2hex(random_bytes(32)) . "\n";
        
        // 8. Attempt to write file, handle gracefully if permissions block it
        if (@file_put_contents(ROOT_DIR . '/.env', $envData) === false) {
            echo json_encode([
                'success' => true, 
                'requires_manual_env' => true,
                'env_content' => $envData,
                'env_path' => ROOT_DIR . '/.env'
            ]);
            exit;
        }

        echo json_encode(['success' => true, 'requires_manual_env' => false]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}