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

// Function to create URL-friendly slugs
function generateSlug($string)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', strtolower($string));
    return trim($slug, '-');
}

if (isset($_POST['submit'])) {
    if (isset($_FILES['Image']) && $_FILES['Image']['error'] === 0) {
        // Generate unique image name
        $originalName = $_FILES['Image']['name'];
        $img_tmp = $_FILES['Image']['tmp_name'];
        $ext = pathinfo($originalName, PATHINFO_EXTENSION);
        $Image = 'blog_' . time() . '.' . $ext;
        $img_path = "./assets/images/blog/" . $Image;

        // Escape inputs
        $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
        $checkSlug = mysqli_query($con, "SELECT COUNT(*) as total FROM blog WHERE slug = '$slug'");
        $row = mysqli_fetch_assoc($checkSlug);
        if ($row['total'] > 0) {
            $slug .= '-' . time();
        }

        $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']);
        $blog_writer = mysqli_real_escape_string($con, $_POST['blog_writer']);
        $blog_date = mysqli_real_escape_string($con, $_POST['blog_date']);
        $category = mysqli_real_escape_string($con, $_POST['category']);

        // Insert query
        $sql = "INSERT INTO `blog` (`Image`, `title`, `slug`, `description`, `meta_title`, `short_des`, `meta_des`, `meta_key`, `blog_writer`, `blog_date`, `category`) 
                VALUES ('$Image', '$title', '$slug', '$description', '$meta_title', '$short_des', '$meta_des', '$meta_key', '$blog_writer', '$blog_date', '$category')";

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

        if ($query) {
            if (move_uploaded_file($img_tmp, $img_path)) {
                header("Location: viewblog.php");
                exit();
            } else {
                echo "❌ Failed to move uploaded image.";
            }
        } else {
            echo "❌ Database Error: " . mysqli_error($con);
        }
    } else {
        echo "❌ No image uploaded or upload error.";
    }
}
?>


<?php include("header.php") ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>ADD blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <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;
    }

    .filepath {
        display: none;
    }

    img[alt="img"] {
        width: clamp(50px, 15%, 100px);
        aspect-ratio: 1/0.70;
    }
    </style>
</head>

<body data-sidebar="dark">

    <div id="layout-wrapper">
        <div class="w-80 ">
            <div class="page-content" style="width: 80%;margin-left: 260px;">
                <div class="container">

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">

                                    <form class="form" action="" method="POST" enctype="multipart/form-data">
                                        <div class="text-center">
                                            <!-- Center container -->
                                            <div
                                                class="dropzone d-flex flex-column align-items-center justify-content-center p-4">
                                                <div class="fallback">
                                                    <input placeholder="Image" name="Image" type="file" required />
                                                </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>

                                            <div class="filepath mt-3" style="display:none;">
                                                <img id="previewImg" src="" alt="img" class="img-fluid"
                                                    style="max-height:150px;">
                                                <div id="filename" class="mt-2"></div>
                                            </div>
                                        </div>


                                        <div class="row">
                                            <div class="col-lg-6">
                                                <label>Title</label>
                                                <input type="text" class="form-control" id="title" name="title"
                                                    placeholder="Enter Your title" onkeyup="generateSlug()" />
                                            </div>
                                            <div class="col-lg-6">
                                                <label>Slug</label>
                                                <input type="text" class="form-control" name="slug" id="slug"
                                                    placeholder="Enter Your 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"
                                                    placeholder="Enter Your meta title" />
                                            </div>
                                            <div class="col-lg-6">
                                                <label>Meta Keyword</label>
                                                <input type="text" class="form-control" name="meta_key"
                                                    placeholder="Enter Your meta keyword" />
                                            </div>
                                        </div>
                                        <br>

                                        <!-- NEW: Writer, Date, Category in one row -->
                                        <div class="row">
                                            <div class="col-lg-4">
                                                <label>Writer</label>
                                                <input type="text" class="form-control" name="blog_writer"
                                                    placeholder="Enter Writer Name" />
                                            </div>
                                            <div class="col-lg-4">
                                                <label>Date</label>
                                                <input type="date" class="form-control" name="blog_date" />
                                            </div>
                                            <div class="col-lg-4">
                                                <label>Category</label>
                                                <select name="category" class="form-control" required>
                                                    <option value="">Select Category</option>
                                                    <option value="uPVC Door">uPVC Door</option>
                                                    <option value="uPVC Window">uPVC Window</option>
                                                    <option value="Aluminium Door">Aluminium Door</option>
                                                </select>
                                            </div>
                                        </div>
                                        <br>


                                        <label>Short Description</label>
                                        <textarea name="short_des" id="Experience1"></textarea>
                                        <br>
                                        
                                        <label>Description</label>
                                        <textarea name="description" id="Experience"></textarea>
                                        <br>

                                        

                                        <label>Meta Description</label>
                                        <textarea name="meta_des" id="Experience2"></textarea>

                                        <div class="text-center mt-4">
                                            <button type="submit" name="submit" class="btn btn-primary"
                                                value="submit">Submit</button>
                                            <a href="viewblog.php"><button type="button" class="btn btn-danger">View
                                                    Data</button></a>
                                        </div>

                                    </form>

                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>


    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="./ck editor/ckeditor.js"></script>
    <script>
    ['Experience', 'Experience1', 'Experience2'].forEach(function(id) {
        CKEDITOR.replace(id);
    });

    var img = document.querySelector("input[name='Image']");
    document.getElementById('upload').onclick = () => {
        img.click();
    }
    img.oninput = () => {
        document.getElementById('filename').innerHTML = img.value.replace(/(C:\\fakepath\\)/, "");
        document.querySelector(".filepath").style.display = 'block';
        let file = img.files[0];
        document.querySelector("img[alt='img']").src = URL.createObjectURL(file);
    }

    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;
    }
    </script>
</body>

</html>