<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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'] ?? '');

    // 1) First insert record WITHOUT image (so we can get ID)
    $insertSql = "INSERT INTO `about_us`
                    (`short_heading`, `main_heading`, `short_description`, `description`)
                  VALUES (
                    '$short_heading',
                    '$main_heading',
                    '$short_description',
                    '$description'
                  )";

    if (mysqli_query($con, $insertSql)) {

        $lastId = mysqli_insert_id($con); // new about_us ID
        $imageName = null;

        // 2) If image selected, upload to folder: assets/images/about/about_ID/
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {

            $uploadDir = "./assets/images/about/";

            // Create folder if not exists
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $originalName = $_FILES['image']['name'];
            $img_tmp      = $_FILES['image']['tmp_name'];
            $extension    = pathinfo($originalName, PATHINFO_EXTENSION);

            // Unique image name
            $imageName = time() . '_' . uniqid('about_') . '.' . $extension;
            $img_path  = $uploadDir . $imageName;

            if (move_uploaded_file($img_tmp, $img_path)) {
                // 3) Update record with image name only
                $imageSql  = mysqli_real_escape_string($con, $imageName);
                $updateImg = "UPDATE `about_us` SET `image` = '$imageSql' WHERE `id` = $lastId";
                mysqli_query($con, $updateImg);
            } else {
                // Upload failed – optional: you can show message
                // echo "<div class='alert alert-warning m-3'>Image upload failed.</div>";
            }
        }

        // 4) Finally redirect to list
        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">Add 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>

                                    <img id="imagePreview" src="#" alt="Image preview"
                                         class="img-thumbnail mt-2"
                                         style="max-height:180px; display:none;">
                                </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"
                                               placeholder="Enter 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"
                                               placeholder="Enter 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"
                                           placeholder="Enter short description">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea name="description" id="description" rows="6" class="form-control"
                                              placeholder="Enter detailed description"></textarea>
                                </div>

                                <div class="text-center mt-4">
                                    <button type="submit" name="submit" class="btn btn-primary">
                                        Submit
                                    </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
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) {
            imagePreview.style.display = 'none';
            imagePreview.src = '#';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(event) {
            imagePreview.src = event.target.result;
            imagePreview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    });
}
</script>
