<?php
include("connection.php");

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Fetch data
$sql = "SELECT * FROM service WHERE id = '$id'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($query);

// Slug generator
function generateSlug($string)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', strtolower($string));
    return trim($slug, '-');
}

if (isset($_POST['update'])) {

    $title = mysqli_real_escape_string($con, $_POST['title']);
    $inputSlug = mysqli_real_escape_string($con, $_POST['slug']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $old_image = $_POST['old_image'];

    // slug handling
    $slug = !empty($inputSlug) ? generateSlug($inputSlug) : generateSlug($title);

    // duplicate slug check
    $checkSlug = mysqli_query($con, "SELECT COUNT(*) as total FROM service WHERE slug='$slug' AND id != '$id'");
    $slugRow = mysqli_fetch_assoc($checkSlug);

    if ($slugRow['total'] > 0) {
        $slug .= '-' . time();
    }

    // MAIN IMAGE UPLOAD
    if (!empty($_FILES['Image']['name'])) {

        $ext = pathinfo($_FILES['Image']['name'], PATHINFO_EXTENSION);
        $Image = time() . '_' . uniqid() . '.' . $ext;

        $path = "./assets/images/service/" . $Image;

        if (move_uploaded_file($_FILES['Image']['tmp_name'], $path)) {
            if (!empty($old_image) && file_exists("./assets/images/service/" . $old_image)) {
                unlink("./assets/images/service/" . $old_image);
            }
        }
    } else {
        $Image = $old_image;
    }

    // SERVICE ARRAY
    $services = [];
    $existing_imgs = $_POST['existing_img'] ?? [];

    if (!empty($_POST['content'])) {

        foreach ($_POST['content'] as $i => $content) {

            $content = mysqli_real_escape_string($con, $content);

            $fileName = $_FILES['Ser_img']['name'][$i] ?? '';
            $tmpName = $_FILES['Ser_img']['tmp_name'][$i] ?? '';

            $finalImg = $existing_imgs[$i] ?? '';

            if (!empty($fileName)) {
                $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                $finalImg = time() . '_' . uniqid() . '.' . $ext;

                move_uploaded_file($tmpName, "./assets/images/service/" . $finalImg);
            }

            if (!empty($content)) {
                $services[] = [
                    'Ser_img' => $finalImg,
                    'content' => $content
                ];
            }
        }
    }

    $services_json = json_encode($services, JSON_UNESCAPED_SLASHES);

    // UPDATE QUERY
    $sql1 = "UPDATE service SET 
                Image='$Image',
                title='$title',
                slug='$slug',
                description='$description',
                services_data='$services_json'
            WHERE id='$id'";

    $query1 = mysqli_query($con, $sql1);

    if ($query1) {
        header("Location: viewservice.php");
        exit();
    } else {
        echo "Update failed: " . mysqli_error($con);
    }
}
?>




<?php
include("header.php")
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Service Update</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta content="" name="description" />
    <meta content="" name="author" />
    <!-- App favicon -->
    <!-- <link rel="shortcut icon" href="assets/images/favicon.ico" /> -->

    <!-- Plugins css -->
    <link href="assets/libs/dropzone/dropzone.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">
    <link rel="shortcut icon" href="./assets/logo/fav.png" />

    <!-- Bootstrap Css -->
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <!-- Icons Css -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <!-- App Css-->
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <!-- App js -->
    <!-- <script src="assets/js/plugin.js"></script> -->
    <style>
        .form .input {
            width: 100%;
            background: white;
            border: none;
            padding: 15px 20px;
            border-radius: 20px;
            margin-bottom: 9px;
            margin-top: 15px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            border-inline: 2px solid transparent;
        }

        input[name='Image'] {
            display: none;

        }

        div#upload {
            cursor: pointer;

        }

        ::-webkit-file-upload-button {
            display: none;
        }

        /* 
        .form .input::-moz-placeholder {
            color: rgb(170, 170, 170);
        }

        .form .input::placeholder {
            color: rgb(170, 170, 170);
        }

        .form .input:focus {
            outline: none;
            border-inline: 2px solid #12b1d1;
        } */

        .filepath {
            display: none;
        }

        img[alt="img"] {
            width: clamp(50px, 15%, 100px);
            aspect-ratio: 1/0.70;
        }
    </style>
</head>

<body data-sidebar="dark">
    <!-- <body data-layout="horizontal" data-topbar="dark"> -->

    <!-- Begin page -->
    <div id="layout-wrapper">

        <div class="w-80 ">
            <div class="page-content" style="width: 80%;margin-left: 260px;">
                <div class="container">
                    <!-- 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">Service Update</h4>


                            </div>
                        </div>
                    </div>
                    <!-- end page title -->

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">

                                    <div>
                                        <form class="form" action="" method="POST" enctype="multipart/form-data">
                                            <!-- Hidden for old image -->
                                            <input type="hidden" name="old_image" value="<?php echo $row['Image']; ?>">

                                            <div class="dropzone">
                                                <div class="fallback">
                                                    <input type="file" name="Image" id="imageInput" />
                                                </div>
                                                <div class="dz-message needsclick" id="upload">
                                                    <div class="mb-3">
                                                        <i class="display-4 text-muted bx bxs-cloud-upload"></i>
                                                    </div>
                                                    <h4>Drop files here or click to upload.</h4>
                                                </div>
                                            </div>

                                            <ul class="list-unstyled mb-0" id="dropzone-preview"></ul>

                                            <!-- Preview -->
                                            <div class="filepath" style="display:block; margin-top:10px;">
                                                <img id="previewImg" src="./assets/images/service/<?php echo $row['Image']; ?>" alt="img" style="max-height:150px;">
                                                <span id="filename"><?php echo $row['Image']; ?></span>
                                            </div>

                                            <br>

                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <label for="">Title</label>
                                                    <input type="text" class="form-control" id="title" name="title" value="<?php echo $row['title']; ?>" placeholder="Enter Your title" onkeyup="generateSlug()" />
                                                </div>

                                                <div class="col-lg-6">
                                                    <label for="">Slug</label>
                                                    <input type="text" class="form-control" id="slug" name="slug" value="<?php echo $row['slug']; ?>" placeholder="Enter Your slug" />
                                                </div>
                                            </div>
                                            <br>

                                            <label for="">Description</label>
                                            <textarea name="description" id="Experience"><?php echo htmlspecialchars($row['description'] ?? ''); ?></textarea>

                                            <br>
                                            <?php $services = json_decode($row['services_data'], true); ?>

                                            <div class="mb-3 text-end">
                                                <button type="button" class="btn btn-info" onclick="addOption()">+ Add Service</button>
                                            </div>

                                            <div id="addOption">

                                                <?php if (!empty($services)) { ?>
                                                    <?php foreach ($services as $index => $entry) { ?>

                                                        <div class="row align-items-center mb-2">

                                                            <div class="col-lg-5">
                                                                <label>Current Image</label><br>

                                                                <?php if (!empty($entry['Ser_img'])) { ?>
                                                                    <img src="./assets/images/service/<?= htmlspecialchars($entry['Ser_img']) ?>" height="50">
                                                                <?php } ?>

                                                                <input type="hidden" name="existing_img[]" value="<?= htmlspecialchars($entry['Ser_img']) ?>">
                                                                <input class="form-control mt-2" type="file" name="Ser_img[]">
                                                            </div>

                                                            <div class="col-lg-5">
                                                                <label>Content</label>
                                                                <input type="text"
                                                                    class="form-control"
                                                                    name="content[]"
                                                                    value="<?= htmlspecialchars($entry['content']) ?>"
                                                                    required>
                                                            </div>

                                                            <div class="col-lg-2 mt-4">
                                                                <button type="button" class="btn btn-danger"
                                                                    onclick="this.parentElement.parentElement.remove()">
                                                                    Remove
                                                                </button>
                                                            </div>

                                                        </div>

                                                    <?php } ?>
                                                <?php } ?>

                                            </div>

                                            <div class="text-center mt-4">
                                                <button type="submit" name="update" class="btn btn-primary" value="submit">
                                                    Update
                                                </button>
                                                <a href="viewservice.php"><button type="button" class="btn btn-danger">View Data</button></a>
                                            </div>
                                        </form>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <!-- end col -->
                    </div>
                    <!-- end row -->
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->


        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->




    <!-- JAVASCRIPT -->
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/metismenu/metisMenu.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>

    <!-- Plugins js -->
    <script src="assets/libs/dropzone/dropzone-min.js"></script>

    <!-- Form file upload init js -->
    <script src="assets/js/pages/form-file-upload.init.js"></script>

    <script src="assets/js/app.js"></script>
    <script src="./ck editor/ckeditor.js"></script>
    <script>
        ['Experience', 'Experience1', 'Experience2', 'Experience3'].forEach(function(id) {
            CKEDITOR.replace(id);
        });
    </script>
    <script>
        const imgInput = document.querySelector("input[name='Image']");
        const uploadBox = document.getElementById('upload');
        const previewImg = document.getElementById('previewImg');
        const filenameSpan = document.getElementById('filename');

        uploadBox.onclick = () => imgInput.click();

        imgInput.onchange = () => {
            if (imgInput.files.length > 0) {
                const file = imgInput.files[0];
                const fileURL = URL.createObjectURL(file);
                previewImg.src = fileURL;
                filenameSpan.textContent = file.name;
                document.querySelector(".filepath").style.display = 'block';
            }
        };
    </script>
    <!-- slug auto -->
    <script>
        function generateSlug() {
            let title = document.getElementById("title").value;
            let slug = title.toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '') // Remove invalid chars
                .replace(/\s+/g, '-') // Replace spaces with -
                .replace(/-+/g, '-') // Collapse dashes
                .trim();
            document.getElementById("slug").value = slug;
        }
    </script>
    <!-- end slug -->


    <script>
        function addOption() {
            let div = document.createElement("div");
            div.classList.add("row", "align-items-center", "mb-2");

            div.innerHTML = `
        <div class="col-lg-5">
            <input class="form-control" type="file" name="Ser_img[]">
        </div>

        <div class="col-lg-5">
            <input type="text" class="form-control" name="content[]" placeholder="Enter content" required>
        </div>

        <div class="col-lg-2 mt-2">
            <button type="button" class="btn btn-danger"
                onclick="this.parentElement.parentElement.remove()">
                Remove
            </button>
        </div>
    `;

            document.getElementById("addOption").appendChild(div);
        }
    </script>

</body>

</html>