<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
error_reporting(E_ALL);

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$result = mysqli_query($con, "SELECT * FROM locations WHERE id=$id");
$location = mysqli_fetch_assoc($result);

if (!$location) {
    echo "<div class='alert alert-danger'>Location not found</div>";
    exit;
}

function generateSlug($string) {
    return trim(preg_replace('/[^A-Za-z0-9-]+/', '-', strtolower($string)), '-');
}

$error_message = '';

if (isset($_POST['submit'])) {

    $title = trim($_POST['title']);
    $slug_input = trim($_POST['slug']);

    if ($title == '') {
        $error_message = "Location title is required.";
    } else {

        $slugBase = $slug_input != '' ? $slug_input : $title;
        $slug = mysqli_real_escape_string($con, generateSlug($slugBase));

        $check = mysqli_query($con, "SELECT id FROM locations WHERE slug='$slug' AND id!=$id");
        if (mysqli_num_rows($check) > 0) {
            $slug .= '-' . time();
        }

        // IMAGE REPLACE LOGIC
        $imageName = $location['image'];

        if (!empty($_FILES['image']['name'])) {

            $uploadDir = "./assets/images/locations/";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

            if (!empty($location['image'])) {
                $oldImagePath = $uploadDir . $location['image'];
                if (file_exists($oldImagePath)) unlink($oldImagePath);
            }

            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $imageName = time() . '_' . uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $imageName);
        }

        $short_desc = mysqli_real_escape_string($con, $_POST['short_desc']);
        $description = mysqli_real_escape_string($con, $_POST['description']);

        $update = "UPDATE locations SET
                    title='$title',
                    slug='$slug',
                    image='$imageName',
                    short_desc='$short_desc',
                    description='$description'
                   WHERE id=$id";

        if (mysqli_query($con, $update)) {
            header("Location: view_locations.php");
            exit;
        } else {
            $error_message = mysqli_error($con);
        }
    }
}
?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid mb-5">

            <h4 class="mb-4">Edit Location</h4>

            <?php if($error_message): ?>
            <div class="alert alert-danger"><?= $error_message ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">

                <div class="row mb-3">
                    <div class="col-md-4">
                        <label>Location Title</label>
                        <input type="text" name="title" id="title" class="form-control"
                            value="<?= htmlspecialchars($location['title']); ?>" onkeyup="generateSlug()" required>
                    </div>

                    <div class="col-md-4">
                        <label>Slug</label>
                        <input type="text" name="slug" id="slug" class="form-control"
                            value="<?= htmlspecialchars($location['slug']); ?>">
                    </div>

                        <!-- <div class="col-md-4">
                            <label>Location Image</label>
                            <input type="file" name="image" class="form-control">
                            <?php if($location['image']): ?>
                            <img src="./assets/images/locations/<?= $location['image']; ?>" class="img-thumbnail mt-2"
                                style="max-height:120px;">
                            <?php endif; ?>
                        </div> -->
                </div>

                <div class="mb-3">
                    <label>Short Description</label>
                    <textarea name="short_desc" id="short_desc" class="form-control">
        <?= htmlspecialchars($location['short_desc']); ?>
    </textarea>
                </div>

                <div class="mb-3">
                    <label>Description</label>
                    <textarea name="description" id="description" class="form-control">
        <?= htmlspecialchars($location['description']); ?>
    </textarea>
                </div>

                <button type="submit" name="submit" class="btn btn-primary">Update</button>
                <a href="view_locations.php" class="btn btn-danger">Back</a>

            </form>
        </div>
    </div>
</div>

<?php include("footer.php"); ?>
<script src="./ck editor/ckeditor.js"></script>
<script>
CKEDITOR.replace('short_desc');
CKEDITOR.replace('description');

function generateSlug() {
    let title = document.getElementById("title").value;
    document.getElementById("slug").value = title.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-+|-+$/g, '');
}
</script>