<?php
include 'header.php';
require_once '../db/config.php';

// Check if the user is logged in as an admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: index.php');
    exit;
}

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $description = $_POST['description'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $selected_cuisines = $_POST['cuisines'] ?? [];
    $id = $_POST['id'] ?? null;

    if ($name && !empty($selected_cuisines) && $id) {
        try {
            $pdo->beginTransaction();

            // Update restaurants table
            $stmt = $pdo->prepare("UPDATE restaurants SET name = ?, description = ?, image_url = ? WHERE id = ?");
            $stmt->execute([$name, $description, $image_url, $id]);

            // Delete existing cuisine associations
            $delete_stmt = $pdo->prepare("DELETE FROM restaurant_cuisines WHERE restaurant_id = ?");
            $delete_stmt->execute([$id]);

            // Insert new cuisine associations
            $cuisine_stmt = $pdo->prepare("INSERT INTO restaurant_cuisines (restaurant_id, cuisine_id) VALUES (?, ?)");
            foreach ($selected_cuisines as $cuisine_id) {
                $cuisine_stmt->execute([$id, $cuisine_id]);
            }

            $pdo->commit();
            header('Location: index.php');
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error updating restaurant: " . $e->getMessage();
        }
    } else {
        $error = "Name and at least one cuisine are required.";
    }
}

// Fetch restaurant details
$stmt = $pdo->prepare("SELECT * FROM restaurants WHERE id = ?");
$stmt->execute([$id]);
$restaurant = $stmt->fetch();

if (!$restaurant) {
    header('Location: index.php');
    exit;
}

// Fetch all cuisines
$cuisines_stmt = $pdo->query("SELECT * FROM cuisines ORDER BY name ASC");
$cuisines = $cuisines_stmt->fetchAll();

// Fetch this restaurant's cuisines
$restaurant_cuisines_stmt = $pdo->prepare("SELECT cuisine_id FROM restaurant_cuisines WHERE restaurant_id = ?");
$restaurant_cuisines_stmt->execute([$id]);
$restaurant_cuisine_ids = $restaurant_cuisines_stmt->fetchAll(PDO::FETCH_COLUMN);

?>

<div class="container mt-4">
    <h2>Edit Restaurant</h2>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <form action="edit_restaurant.php?id=<?php echo $restaurant['id']; ?>" method="POST">
        <input type="hidden" name="id" value="<?php echo $restaurant['id']; ?>">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($restaurant['name']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea class="form-control" id="description" name="description"><?php echo htmlspecialchars($restaurant['description']); ?></textarea>
        </div>
        <div class="mb-3">
            <label class="form-label">Cuisines</label>
            <div class="row">
                <?php foreach ($cuisines as $cuisine): ?>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="cuisines[]" value="<?php echo $cuisine['id']; ?>" id="cuisine_<?php echo $cuisine['id']; ?>" <?php echo in_array($cuisine['id'], $restaurant_cuisine_ids) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="cuisine_<?php echo $cuisine['id']; ?>">
                                <?php echo htmlspecialchars($cuisine['name']); ?>
                            </label>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="mb-3">
            <label for="image_url" class="form-label">Image URL</label>
            <input type="text" class="form-control" id="image_url" name="image_url" value="<?php echo htmlspecialchars($restaurant['image_url']); ?>">
        </div>
        <button type="submit" class="btn btn-primary">Update Restaurant</button>
        <a href="index.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include 'footer.php'; ?>