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

$response = ['success' => false, 'message' => '', 'data' => []];

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

$host     = isset($_POST['host']) ? trim($_POST['host']) : '';
$dbname   = isset($_POST['dbname']) ? trim($_POST['dbname']) : '';
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';

if (empty($host) || empty($dbname) || empty($username)) {
    $response['message'] = 'Database credentials are required.';
    echo json_encode($response);
    exit;
}

$sqlFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'tap2order.sql';

if (!file_exists($sqlFile)) {
    $response['message'] = 'SQL file not found at: ' . basename($sqlFile);
    echo json_encode($response);
    exit;
}

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

    $sql = file_get_contents($sqlFile);
    if ($sql === false) {
        $response['message'] = 'Failed to read SQL file.';
        echo json_encode($response);
        exit;
    }

    $sql = str_replace('USE `tap2order`;', '', $sql);

    $statements = array_filter(
        array_map('trim', explode(';', $sql)),
        function ($s) { return !empty($s) && $s !== '--'; }
    );

    $tablesCreated = [];
    $errors = [];

    foreach ($statements as $statement) {
        $statement = trim($statement);
        if (empty($statement)) continue;

        if (preg_match('/^--/', $statement) && strpos($statement, "\n") === false) continue;
        if (preg_match('/^SET /i', $statement)) {
            try {
                $pdo->exec($statement);
            } catch (PDOException $e) {}
            continue;
        }

        if (preg_match('/^DROP DATABASE/i', $statement)) continue;
        if (preg_match('/^CREATE DATABASE/i', $statement)) {
            try {
                $pdo->exec($statement);
                $pdo->exec("USE `{$dbname}`");
            } catch (PDOException $e) {}
            continue;
        }

        if (preg_match('/^CREATE TABLE\s+`?(\w+)`?/i', $statement, $m)) {
            $tableName = $m[1];
            try {
                $pdo->exec($statement);
                $tablesCreated[] = $tableName;
            } catch (PDOException $e) {
                $errors[] = "{$tableName}: " . $e->getMessage();
            }
            continue;
        }

        if (preg_match('/^INSERT INTO/i', $statement)) {
            try {
                $pdo->exec($statement);
            } catch (PDOException $e) {
                if (strpos($e->getMessage(), 'Duplicate entry') === false) {
                    $errors[] = 'Insert error: ' . substr($e->getMessage(), 0, 200);
                }
            }
            continue;
        }

        try {
            $pdo->exec($statement);
        } catch (PDOException $e) {}
    }

    $pdo->exec("USE `{$dbname}`");

    $response['success'] = true;
    $response['message'] = 'Database installed successfully! ' . count($tablesCreated) . ' tables created.';
    $response['data'] = [
        'tables' => $tablesCreated,
        'errors' => $errors,
        'table_count' => count($tablesCreated),
    ];

} catch (PDOException $e) {
    $response['message'] = 'Database error: ' . $e->getMessage();
}

echo json_encode($response);
exit;
