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

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;
}

$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';

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

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email address.']);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters.']);
    exit;
}

if (empty($_SESSION['install_db'])) {
    echo json_encode(['success' => false, 'message' => 'Database configuration not found. Please go back to Step 2.']);
    exit;
}

$dbConfig = $_SESSION['install_db'];

try {
    $dsn = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']};charset=utf8mb4";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, password = ? WHERE id = 1");
    $stmt->execute([$name, $email, $hashedPassword]);

    if ($stmt->rowCount() === 0) {
        $stmt = $pdo->prepare("INSERT INTO users (id, role_id, name, email, password, status, is_demo, created_at, updated_at) VALUES (1, 1, ?, ?, ?, 'active', 0, NOW(), NOW()) ON DUPLICATE KEY UPDATE name = VALUES(name), email = VALUES(email), password = VALUES(password), updated_at = NOW()");
        $stmt->execute([$name, $email, $hashedPassword]);
    }

    $_SESSION['install_admin'] = ['name' => $name, 'email' => $email];

    echo json_encode(['success' => true, 'message' => 'Admin account created successfully.']);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
