<?php
session_start();

// Enable error logging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load configuration
$config = include(__DIR__ . '/../../config.php');

// Get the website ID from the session
$websiteId = $_SESSION['websiteId'] ?? 1;

// Find the website configuration
$websiteConfig = array_filter($config, function($site) use ($websiteId) {
    return isset($site['id']) && $site['id'] === $websiteId;
});
$websiteConfig = reset($websiteConfig);

// Connect to SQLite database
$db = new SQLite3($websiteConfig['database']);

// Get the table and ID from the request
$table = $_GET['table'] ?? '';
$id = $_GET['id'] ?? 0;

// Debug: Get the table schema
$schema = $db->querySingle("SELECT sql FROM sqlite_master WHERE name='$table';");

// Check if the ID exists
$checkId = $db->querySingle('SELECT COUNT(*) FROM "' . $table . '" WHERE "id" = ' . (int) $id);
if ($checkId == 0) {
    $idError = "No row found for ID $id in table $table.";
}

// Fetch columns
$columns = [];
$columnsResult = $db->query('PRAGMA table_info("' . $table . '")');
while ($row = $columnsResult->fetchArray(SQLITE3_ASSOC)) {
    $columns[] = $row['name'];
}

// Fetch row
$stmt = $db->prepare('SELECT * FROM "' . $table . '" WHERE "id" = :id');
$stmt->bindValue(':id', (int) $id, SQLITE3_INTEGER);
$result = $stmt->execute();

$row = $result ? $result->fetchArray(SQLITE3_ASSOC) : null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_changes'])) {
    foreach ($columns as $column) {
        if (!isset($_POST[$column])) continue;

        $value = $_POST[$column] ?: null;
        if ($column === 'date' && empty($value)) {
            $value = date('Y-m-d H:i:s');
        }

        $updateStmt = $db->prepare('UPDATE "' . $table . '" SET "' . $column . '" = :value WHERE "id" = :id');
        $updateStmt->bindValue(':id', (int) $id, SQLITE3_INTEGER);
        $updateStmt->bindValue(':value', $value, SQLITE3_TEXT);
        $updateStmt->execute();
    }
    header("Location: edit_database.php?table=" . urlencode($table));
    exit();
}

// Handle Fix IDs
if (isset($_POST['fix_ids'])) {
    // Step 1: Create a backup table
    $db->exec('CREATE TABLE IF NOT EXISTS "content_backup" AS SELECT * FROM "content"');

    // Step 2: Add a new ID column with auto-increment
    $db->exec('ALTER TABLE "content" RENAME TO "content_old"');
    $db->exec('CREATE TABLE "content" (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        page TEXT,
        title TEXT,
        content TEXT,
        date TEXT,
        parent TEXT
    )');

    // Step 3: Copy data and reassign IDs
    $db->exec('INSERT INTO "content" (page, title, content, date, parent)
               SELECT page, title, content, date, parent FROM "content_old"');

    // Step 4: Remove old table
    $db->exec('DROP TABLE "content_old"');

    header("Location: edit_database.php?table=content&fix_success=1");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Row</title>
</head>
<body>
    <h1>Edit Row in Table: <?php echo htmlspecialchars($table); ?></h1>

    <?php if (isset($idError)): ?>
        <p style="color: red;"><?php echo $idError; ?></p>
        <form method="post">
            <button type="submit" name="fix_ids">Fix ID Issues</button>
        </form>
    <?php else: ?>
        <form method="post">
            <?php foreach ($columns as $column): ?>
                <label for="<?php echo htmlspecialchars($column); ?>"><?php echo htmlspecialchars($column); ?>:</label>
                <?php if ($column === 'content'): ?>
                    <textarea id="<?php echo htmlspecialchars($column); ?>" name="<?php echo htmlspecialchars($column); ?>" style="resize: both;"><?php echo htmlspecialchars($row[$column] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                <?php else: ?>
                    <input type="text" id="<?php echo htmlspecialchars($column); ?>" name="<?php echo htmlspecialchars($column); ?>" value="<?php echo htmlspecialchars($row[$column] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                <?php endif; ?>
                <br>
            <?php endforeach; ?>
            <button type="submit" name="save_changes">Save Changes</button>
        </form>
    <?php endif; ?>

    <a href="edit_database.php?table=<?php echo htmlspecialchars($table); ?>">Back to Table</a>
</body>
</html>