<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Get ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    echo "<div class='alert alert-danger m-3'>Invalid request.</div>";
    include("footer.php");
    exit;
}

// Fetch existing record
$query = "SELECT * FROM `about_us` WHERE id = $id LIMIT 1";
$result = mysqli_query($con, $query);

if (!$result || mysqli_num_rows($result) == 0) {
    echo "<div class='alert alert-danger m-3'>Record not found.</div>";
    include("footer.php");
    exit;
}

$about = mysqli_fetch_assoc($result);
$currentImage = $about['image'] ?? null;

// Handle form submit
if (isset($_POST['submit'])) {

    $short_heading     = mysqli_real_escape_string($con, $_POST['short_heading'] ?? '');
    $main_heading      = mysqli_real_escape_string($con, $_POST['main_heading'] ?? '');
    $short_description = mysqli_real_escape_string($con, $_POST['short_description'] ?? '');
    $description       = mysqli_real_escape_string($con, $_POST['description'] ?? '');

    $uploadDir  = "./assets/images/about/";
    $imageName  = $currentImage; // keep old image by default

    // If new image selected
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $originalName = $_FILES['image']['name'];
        $img_tmp      = $_FILES['image']['tmp_name'];
        $extension    = pathinfo($originalName, PATHINFO_EXTENSION);

        $newImageName = time() . '_' . uniqid('about_') . '.' . $extension;
        $img_path     = $uploadDir . $newImageName;

        if (move_uploaded_file($img_tmp, $img_path)) {
            // Delete old image
            if (!empty($currentImage) && file_exists($uploadDir . $currentImage)) {
                @unlink($uploadDir . $currentImage);
            }
            $imageName = $newImageName;
        }
    }

    // Build update query (without is_active)
    $imageSql = $imageName ? "'" . mysqli_real_escape_string($con, $imageName) . "'" : "NULL";

    $sql = "UPDATE `about_us` SET
                `image`             = $imageSql,
                `short_heading`     = '$short_heading',
                `main_heading`      = '$main_heading',
                `short_description` = '$short_description',
                `description`       = '$description'
            WHERE id = $id";

    if (mysqli_query($con, $sql)) {
        header("Location: viewabout.php");
        exit();
    } else {
        echo "<div class='alert alert-danger m-3'>Database Error: " . mysqli_error($con) . "</div>";
    }
}
?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">

            <!-- start page title -->
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                        <h4 class="mb-sm-0 font-size-18">Edit About Content</h4>
                    </div>
                </div>
            </div>
            <!-- end page title -->

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">

                            <form action="" method="POST" enctype="multipart/form-data">

                                <!-- Image with Preview -->
                                <div class="mb-3">
                                    <label class="form-label">Image</label>
                                    <input type="file" name="image" id="imageInput" class="form-control" accept="image/*">
                                    <small class="text-muted d-block">
                                        Recommended: big banner image like home about section.
                                    </small>

                                    <?php if (!empty($currentImage)) : ?>
                                        <img id="imagePreview"
                                             src="assets/images/about/<?php echo htmlspecialchars($currentImage); ?>"
                                             class="img-thumbnail mt-2"
                                             style="max-height:180px;">
                                    <?php else : ?>
                                        <img id="imagePreview"
                                             src="#"
                                             class="img-thumbnail mt-2"
                                             style="max-height:180px; display:none;">
                                    <?php endif; ?>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Main Heading</label>
                                        <input type="text" name="main_heading" class="form-control"
                                               value="<?php echo htmlspecialchars($about['main_heading']); ?>" required>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Short Heading</label>
                                        <input type="text" name="short_heading" class="form-control"
                                               value="<?php echo htmlspecialchars($about['short_heading']); ?>" required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Short Description</label>
                                    <input type="text" name="short_description" class="form-control"
                                           value="<?php echo htmlspecialchars($about['short_description']); ?>">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" id="description" rows="6"
                                              class="form-control"><?php
                                        echo htmlspecialchars($about['description']);
                                    ?></textarea>
                                </div>

                                <div class="text-center mt-4">
                                    <button type="submit" name="submit" class="btn btn-primary">Update</button>
                                    <a href="viewabout.php" class="btn btn-danger">Back to List</a>
                                </div>

                            </form>

                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <?php include("footer.php"); ?>
</div>

<!-- CKEditor -->
<script src="./ck editor/ckeditor.js"></script>
<script>
    CKEDITOR.replace('description');

    // Image preview on change
    const imageInput   = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');

    if (imageInput) {
        imageInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (!file) {
                return;
            }

            const reader = new FileReader();
            reader.onload = function (event) {
                imagePreview.src = event.target.result;
                imagePreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        });
    }
</script>
