<?php
/**
 * Installation API
 */
header('Content-Type: application/json');
error_reporting(E_ALL);
set_time_limit(0);
ini_set('display_errors', 0);

$input = [];
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $rawInput = file_get_contents('php://input');
    $input = json_decode($rawInput, true);
    if (!is_array($input)) {
        $input = [];
    }
}

$action = $input['action'] ?? $_GET['action'] ?? '';

// Check if already installed
if (file_exists('installed.lock') && $action !== 'check_status') {
    echo json_encode(['success' => false, 'message' => 'System already installed']);
    exit;
}

if ($action === 'check_system') {
    $checks = [
        ['name' => 'PHP Version (>= 7.4)', 'pass' => version_compare(PHP_VERSION, '7.4.0', '>=')],
        ['name' => 'PDO Extension', 'pass' => extension_loaded('pdo')],
        ['name' => 'PDO MySQL Extension', 'pass' => extension_loaded('pdo_mysql')],
        ['name' => 'cURL Extension', 'pass' => extension_loaded('curl')],
        ['name' => 'OpenSSL Extension', 'pass' => extension_loaded('openssl')],
        ['name' => 'mbstring Extension', 'pass' => extension_loaded('mbstring')],
        ['name' => 'GD Extension', 'pass' => extension_loaded('gd')],
        ['name' => 'Config Directory Writable', 'pass' => is_writable('../')]
    ];
    echo json_encode(['success' => true, 'data' => $checks]);
    exit;
}

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

    if (empty($host) || empty($name) || empty($user)) {
        echo json_encode(['success' => false, 'message' => 'Please provide database host, name, and username.']);
        exit;
    }

    try {
        // Connect to MySQL server (without database name) first to verify credentials
        $dsn = "mysql:host=$host;charset=utf8mb4";
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 5 // 5 second timeout for testing
        ]);

        // Create database if it does not exist
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");

        // Select the database
        $pdo->exec("USE `$name`");

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

if ($action === 'finish_install') {
    // 1. Create .env file
    $db_host = $input['db_host'] ?? 'localhost';
    $db_name = $input['db_name'] ?? '';
    $db_user = $input['db_user'] ?? '';
    $db_pass = $input['db_pass'] ?? '';
    $app_name = $input['app_name'] ?? 'Madrasa Management System';
    $app_url = $input['app_url'] ?? 'http://localhost';
    $app_timezone = $input['app_timezone'] ?? 'Asia/Karachi';

    if (empty($db_host) || empty($db_name) || empty($db_user)) {
        echo json_encode(['success' => false, 'message' => 'Please provide database host, name, and username.']);
        exit;
    }

    $envContent = "# Database Configuration\n";
    $envContent .= "DB_HOST=" . ($db_host ?: 'localhost') . "\n";
    $envContent .= "DB_DATABASE=" . $db_name . "\n";
    $envContent .= "DB_USERNAME=" . $db_user . "\n";
    $envContent .= "DB_PASSWORD=\"" . $db_pass . "\"\n\n";

    $envContent .= "# Email Configuration\n";
    $envContent .= "MAIL_HOST=" . ($input['mail_host'] ?? '') . "\n";
    $envContent .= "MAIL_PORT=" . ($input['mail_port'] ?? '587') . "\n";
    $envContent .= "MAIL_USERNAME=" . ($input['mail_user'] ?? '') . "\n";
    $envContent .= "MAIL_PASSWORD=\"" . ($input['mail_pass'] ?? '') . "\"\n";
    $envContent .= "MAIL_FROM_ADDRESS=" . ($input['mail_user'] ?? '') . "\n";
    $envContent .= "MAIL_FROM_NAME=\"" . ($app_name) . "\"\n";
    $envContent .= "MAIL_ENCRYPTION=" . ($input['mail_enc'] ?? 'tls') . "\n\n";

    $envContent .= "# Application Settings\n";
    $envContent .= "APP_NAME=\"" . ($app_name) . "\"\n";
    $envContent .= "APP_URL=" . ($app_url) . "\n";
    $envContent .= "APP_ENV=production\n";
    $envContent .= "APP_DEBUG=false\n\n";

    $envContent .= "# Security\n";
    $envContent .= "SESSION_LIFETIME=120\n";
    $envContent .= "CSRF_TOKEN_LIFETIME=3600\n\n";

    $envContent .= "# System\n";
    $envContent .= "TIMEZONE=" . ($app_timezone) . "\n";
    $envContent .= "CURRENCY=PKR\n";
    $envContent .= "TAX_RATE=0.00\n";

    if (file_put_contents('../.env', $envContent) === false) {
        echo json_encode(['success' => false, 'message' => 'Could not write .env file. Check folder permissions.']);
        exit;
    }

    try {
        $dsn = "mysql:host=$db_host;charset=utf8mb4";
        $pdo = new PDO($dsn, $db_user, $db_pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        
        // Create database if it does not exist
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
        
        // Select the database
        $pdo->exec("USE `$db_name`");

        // 2. Import SQL Backup
        $sqlPath = __DIR__ . '/../site/dbBackup/installation_db/madrasa_db_new.sql';
        if (!file_exists($sqlPath)) {
            throw new Exception("Backup file not found at $sqlPath");
        }

        $sqlContent = file_get_contents($sqlPath);

        // Remove comments and split by semicolon
        $queries = array_filter(array_map('trim', explode(';', $sqlContent)));

        foreach ($queries as $query) {
            if (empty($query))
                continue;

            // Skip database creation and usage statements to avoid conflicts
            if (stripos($query, 'CREATE DATABASE') === 0 || stripos($query, 'USE ') === 0) {
                continue;
            }

            try {
                $pdo->exec($query);
            } catch (Throwable $e) {
                // Ignore errors if table already exists or other common issues during re-run
                // But you might want to log them or handle them more strictly
            }
        }

        // 3. Update Admin User (following backup schema: userid, userkey, ownreName)
        $admin_email = $input['admin_email'] ?? '';
        $admin_name = $input['admin_name'] ?? '';
        $admin_pass = $input['admin_pass'] ?? '';
        $hashedPass = password_hash($admin_pass, PASSWORD_BCRYPT);

        // Delete existing admins to avoid conflicts if re-running
        $pdo->exec("DELETE FROM login");
        $stmt = $pdo->prepare("INSERT INTO login (userid, ownreName, userkey) VALUES (?, ?, ?)");
        $stmt->execute([$admin_email, $admin_name, $hashedPass]);

        // 4. Update App Config (following backup schema: M_Name)
        // Ensure record ID 1 exists and update it
        $stmt = $pdo->prepare("INSERT INTO config (id, M_Name) VALUES (1, ?) ON DUPLICATE KEY UPDATE M_Name = VALUES(M_Name)");
        $stmt->execute([$app_name]);

        // 5. Save Email Config (if provided)
        if (!empty($input['mail_host'])) {
            $mail_host = $input['mail_host'] ?? '';
            $mail_port = $input['mail_port'] ?? 587;
            $mail_user = $input['mail_user'] ?? '';
            $mail_pass = $input['mail_pass'] ?? '';
            $mail_enc = $input['mail_enc'] ?? 'tls';

            $pdo->exec("DELETE FROM email_config");
            $stmt = $pdo->prepare("INSERT INTO email_config (smtp_host, smtp_port, email_user, email_pass, email_from, reply_to, encryption, is_default) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?, 1)");
            $stmt->execute([$mail_host, $mail_port, $mail_user, $mail_pass, $mail_user, $mail_user, $mail_enc]);
        }

        // 6. Create lock file
        file_put_contents('installed.lock', date('Y-m-d H:i:s'));

        echo json_encode(['success' => true]);
    } catch (Throwable $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
