<?php

define('SKIP_DB_ERROR', true);

class SetupController {
    public function index() {
        require_once APP_PATH . '/views/setup.php';
    }

    public function run() {
        $host = sanitize($_POST['db_host'] ?? 'localhost');
        $port = sanitize($_POST['db_port'] ?? '3306');
        $dbname = sanitize($_POST['db_name'] ?? 'smartform_db');
        $user = sanitize($_POST['db_user'] ?? 'root');
        $pass = $_POST['db_pass'] ?? '';

        try {
            // Try connecting without DB first
            $pdo = new PDO("mysql:host={$host};port={$port};charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            ]);

            // Create database if not exists
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbname}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `{$dbname}`");

            // Run schema
            $schema = file_get_contents(ROOT_PATH . '/storage/schema.sql');
            $pdo->exec($schema);

            // Update .env
            $envContent = "DB_HOST={$host}\nDB_PORT={$port}\nDB_NAME={$dbname}\nDB_USER={$user}\nDB_PASS={$pass}\n\n";
            $envContent .= "APP_NAME=SmartForm Funnel Builder\nAPP_URL=http://{$_SERVER['HTTP_HOST']}/smartform\nAPP_ENV=production\n\n";
            $envContent .= "UPLOAD_MAX_SIZE=5242880\nUPLOAD_PATH=public/uploads/\n";
            file_put_contents(ROOT_PATH . '/.env', $envContent);

            jsonResponse(['success' => true, 'message' => 'Setup complete! Redirecting...', 'redirect' => url('/')]);
        } catch (PDOException $e) {
            jsonResponse(['success' => false, 'message' => 'Database error: ' . $e->getMessage()], 500);
        }
    }
}
