<?php
include("connection.php");
ini_set('display_errors', '1');
error_reporting(E_ALL);

// Slug generation function
function generateSlug($string)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', strtolower($string));
    return trim($slug, '-');
}

if (!isset($_GET['id'])) {
    die("Invalid request");
}

$id = intval($_GET['id']);

// Fetch existing record
$result = mysqli_query($con, "SELECT * FROM aluminium WHERE id = $id");
$data = mysqli_fetch_assoc($result);

if (!$data) {
    die("Record not found");
}

// Decode services JSON
$services = json_decode($data['services_data'], true);

// Handle update
if (isset($_POST['submit'])) {

    $title = mysqli_real_escape_string($con, $_POST['title']);
    $inputSlug = mysqli_real_escape_string($con, $_POST['slug']);
    $slug = empty($inputSlug) ? generateSlug($title) : generateSlug($inputSlug);

    // Ensure slug is unique (exclude current ID)
    $checkSlug = mysqli_query($con, "SELECT COUNT(*) as total FROM aluminium WHERE slug = '$slug' AND id != $id");
    $row = mysqli_fetch_assoc($checkSlug);
    if ($row['total'] > 0) {
        $slug .= '-' . time(); // Make unique
    }

    $description = mysqli_real_escape_string($con, $_POST['description']);
    $meta_title = mysqli_real_escape_string($con, $_POST['meta_title']);
    $short_des = mysqli_real_escape_string($con, $_POST['short_des']);
    $meta_des = mysqli_real_escape_string($con, $_POST['meta_des']);
    $meta_key = mysqli_real_escape_string($con, $_POST['meta_key']);

    // Rebuild services JSON
    $services = [];
    if (!empty($_POST['heading']) && !empty($_POST['content'])) {
        foreach ($_POST['heading'] as $index => $heading) {
            $headingText = mysqli_real_escape_string($con, $heading);
            $contentText = mysqli_real_escape_string($con, $_POST['content'][$index]);

            if (!empty($headingText) || !empty($contentText)) {
                $services[] = [
                    'heading' => $headingText,
                    'content' => $contentText
                ];
            }
        }
    }

    $services_json = json_encode($services);

    // Update query
    $update = "UPDATE aluminium SET 
        title = '$title',
        slug = '$slug',
        description = '$description',
        meta_title = '$meta_title',
        short_des = '$short_des',
        meta_des = '$meta_des',
        meta_key = '$meta_key',
        services_data = '$services_json'
        WHERE id = $id";

    $query = mysqli_query($con, $update);

    if ($query) {
        header("Location: view_aluminium.php");
        exit();
    } else {
        echo "Error updating: " . 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">Update update Mid Categories</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">
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <label>Title</label>
                                                    <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($data['title']) ?>" onkeyup="generateSlug()" required>
                                                </div>
                                                <div class="col-lg-6">
                                                    <label>Slug</label>
                                                    <input type="text" class="form-control" name="slug" id="slug" value="<?= htmlspecialchars($data['slug']) ?>">
                                                </div>
                                            </div><br>

                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <label>Meta Title</label>
                                                    <input type="text" class="form-control" name="meta_title" value="<?= htmlspecialchars($data['meta_title']) ?>">
                                                </div>
                                                <div class="col-lg-6">
                                                    <label>Meta Keyword</label>
                                                    <input type="text" class="form-control" name="meta_key" value="<?= htmlspecialchars($data['meta_key']) ?>">
                                                </div>
                                            </div><br>

                                            <!-- Service Fields -->
                                            
                                            <div class="text-end">
                                                <button type="button" class="btn btn-primary" onclick="addOption()">+ Add More</button>
                                            </div>
                                            <div id="serviceContainer">
                                                <?php
                                                if (!empty($services)) {
                                                    foreach ($services as $srv) {
                                                ?>
                                                        <div class="row align-items-center mb-2">
                                                            <div class="col-lg-5">
                                                                <label class="form-label">Heading</label>
                                                                <input class="form-control" type="text" name="heading[]" value="<?= htmlspecialchars($srv['heading']) ?>">
                                                            </div>
                                                            <div class="col-lg-5">
                                                                 <label class="form-label">Content</label>
                                                                <textarea class="form-control" name="content[]" rows="3"><?= htmlspecialchars($srv['content']) ?></textarea>
                                                            </div>
                                                            <div class="col-lg-2">
                                                                <button type="button" class="btn btn-danger" onclick="this.parentElement.parentElement.remove()">Remove</button>
                                                            </div>
                                                        </div>
                                                <?php }
                                                } ?>
                                            </div>

                                            

                                            <label>Description</label>
                                            <textarea class="form-control" name="description" id="Experience"><?= htmlspecialchars($data['description']) ?></textarea><br>

                                            <label>Short Description</label>
                                            <textarea class="form-control" name="short_des" id="Experience1"><?= htmlspecialchars($data['short_des']) ?></textarea><br>

                                            <label>Meta Description</label>
                                            <textarea class="form-control" name="meta_des" id="Experience2"><?= htmlspecialchars($data['meta_des']) ?></textarea><br>

                                            <div class="text-center mt-4">
                                                <button type="submit" name="submit" class="btn btn-success">Update</button>
                                                <a href="view_aluminium.php" class="btn btn-secondary">Cancel</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>


    <!-- slug auto -->
    <script>
        function generateSlug() {
            let title = document.getElementById("title").value;
            let slug = title.toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-')
                .trim();
            document.getElementById("slug").value = slug;
        }

        function addOption() {
            const 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="text" name="heading[]" placeholder="Enter Heading">
        </div>
        <div class="col-lg-5">
            <textarea class="form-control" name="content[]" rows="3" placeholder="Enter Content"></textarea>
        </div>
        <div class="col-lg-2">
            <button type="button" class="btn btn-danger" onclick="this.parentElement.parentElement.remove()">Remove</button>
        </div>`;
            document.getElementById('serviceContainer').appendChild(div);
        }
    </script>



    <!--  -->
</body>

</html>