<?php
// api/installer.php
// Handles database initialization, config writing, and admin creation

header('Content-Type: application/json');

// Check if already installed
if (file_exists('../.installed')) {
    echo json_encode(['success' => false, 'message' => 'System already installed. Please remove .installed to reinstall.']);
    exit;
}

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

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

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$name;charset=utf8", $user, $pass);
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $e->getMessage()]);
    }

} elseif ($action === 'install') {
    $host = $_POST['db_host'] ?? '';
    $db_name = $_POST['db_name'] ?? '';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    
    $comp_name = $_POST['company_name'] ?? 'JUSTSALE';
    $curr_code = $_POST['currency_code'] ?? 'USD';
    $curr_name = $_POST['currency_name'] ?? 'US Dollar';
    
    $admin_full = $_POST['admin_fullname'] ?? 'Administrator';
    $admin_user = $_POST['admin_user'] ?? 'admin';
    $admin_pass = $_POST['admin_pass'] ?? '';

    if (empty($admin_pass)) {
        echo json_encode(['success' => false, 'message' => 'Admin password is required.']);
        exit;
    }

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // 1. Run Schema
        $sql = file_get_contents('../database.sql');
        // Filter out existing DB creation since we are already connected to $db_name
        $sql = preg_replace('/CREATE DATABASE IF NOT EXISTS \w+;/', '', $sql);
        $sql = preg_replace('/USE \w+;/', '', $sql);
        
        // Multi-query execution
        $pdo->exec($sql);

        // 2. Clear dummy settings and apply user settings
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")
             ->execute(['company_name', $comp_name]);
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")
             ->execute(['company_currency_code', $curr_code]);
        $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")
             ->execute(['company_currency_name', $curr_name]);

        // 3. Create/Update Admin User
        $hash = password_hash($admin_pass, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("REPLACE INTO users (username, fullname, password_hash, role) VALUES (?, ?, ?, 'Admin')");
        $stmt->execute([$admin_user, $admin_full, $hash]);

        // 4. Write api/db.php
        $db_content = "<?php
// api/db.php - Generated by Setup Wizard
define('SYSTEM_VERSION', '2.0.5');
\$host = '$host';
\$dbname = '$db_name';
\$username = '$db_user';
\$password = '$db_pass'; 

try {
    \$pdo = new PDO(\"mysql:host=\$host;dbname=\$dbname;charset=utf8\", \$username, \$password);
    \$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    \$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException \$e) {
    header('Content-Type: application/json');
    die(json_encode(['success' => false, 'message' => 'Database connection failed.']));
}

// Licensing Gatekeeper
require_once 'license_check_middleware.php';
?>";
        file_put_contents('db.php', $db_content);

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

        echo json_encode(['success' => true]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Installation failed: ' . $e->getMessage()]);
    }
}
