<?php
session_start();
header('Content-Type: application/json');

// Only allow during installation
if (file_exists(__DIR__ . '/installed.lock')) {
    echo json_encode(['success' => false, 'message' => 'Installation already completed.']);
    exit;
}

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

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

$host = isset($input['host']) ? trim($input['host']) : 'localhost';
$dbname = isset($input['dbname']) ? trim($input['dbname']) : '';
$username = isset($input['username']) ? trim($input['username']) : '';
$password = isset($input['password']) ? $input['password'] : '';
$port = isset($input['port']) ? intval($input['port']) : 3306;

if (empty($dbname) || empty($username)) {
    echo json_encode(['success' => false, 'message' => 'Database name and username are required.']);
    exit;
}

// Build the config file content
$configContent = "<?php\n";
$configContent .= "// Database Configuration - Generated by Tap2Order Installer\n";
$configContent .= "define('DB_HOST', " . var_export($host, true) . ");\n";
$configContent .= "define('DB_NAME', " . var_export($dbname, true) . ");\n";
$configContent .= "define('DB_USER', " . var_export($username, true) . ");\n";
$configContent .= "define('DB_PASS', " . var_export($password, true) . ");\n";
$configContent .= "define('DB_PORT', " . var_export($port, true) . ");\n";
$configContent .= "define('DB_CHARSET', 'utf8mb4');\n";

$configPath = dirname(__DIR__) . '/config/database.php';
if (file_put_contents($configPath, $configContent) === false) {
    echo json_encode(['success' => false, 'message' => 'Failed to write config file. Check directory permissions.']);
    exit;
}

$_SESSION['install_db'] = ['host' => $host, 'dbname' => $dbname, 'username' => $username, 'password' => $password, 'port' => $port];

echo json_encode(['success' => true, 'message' => 'Database configuration saved successfully.']);
