<?php require_once('header.php'); ?>

<?php

$error_message = '';
$success_message = '';


/* =========================
   GET BLOG ID
========================= */

if (!isset($_REQUEST['id'])) {

    header('location: logout.php');
    exit;

}

$current_blog_id = $_REQUEST['id'];


/* =========================
   GET BLOG DATA
========================= */

$statement = $pdo->prepare("
    SELECT *
    FROM blogs
    WHERE id=?
");

$statement->execute([
    $current_blog_id
]);

$row = $statement->fetch(PDO::FETCH_ASSOC);


if (!$row) {

    header('location: logout.php');
    exit;

}


/* =========================
   EXISTING DATA
========================= */

$title = $row['title'] ?? '';
$excerpt = $row['excerpt'] ?? '';
$content = $row['content'] ?? '';
$slug = $row['slug'] ?? '';

$meta_title = $row['meta_title'] ?? '';
$meta_keyword = $row['meta_keyword'] ?? '';
$meta_description = $row['meta_description'] ?? '';

$status = $row['status'] ?? 1;
$image = $row['image'] ?? '';


/* =========================
   UPDATE BLOG
========================= */

if (isset($_POST['form1'])) {

    $title = trim($_POST['title'] ?? '');
    $excerpt = $_POST['excerpt'] ?? '';
    $content = $_POST['content'] ?? '';
    $slug = trim($_POST['slug'] ?? '');

    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_keyword = trim($_POST['meta_keyword'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');

    $status = (int)($_POST['status'] ?? 1);

    $valid = 1;


    /* =========================
       IMAGE
    ========================= */

    /*
     * Keep existing image path.
     * Add file stores:
     * assets/images/blog/filename.webp
     */

    $final_image = $image;


    if (
        isset($_FILES['image']) &&
        $_FILES['image']['error'] != UPLOAD_ERR_NO_FILE
    ) {

        $image_name = $_FILES['image']['name'];
        $image_tmp = $_FILES['image']['tmp_name'];
        $image_error = $_FILES['image']['error'];


        if ($image_error != UPLOAD_ERR_OK) {

            $valid = 0;

            $error_message .=
                "There was an error uploading the image.<br>";

        } else {

            $image_ext = strtolower(
                pathinfo(
                    $image_name,
                    PATHINFO_EXTENSION
                )
            );


            $allowed_extensions = [
                'jpg',
                'jpeg',
                'png',
                'gif',
                'webp'
            ];


            if (
                !in_array(
                    $image_ext,
                    $allowed_extensions,
                    true
                )
            ) {

                $valid = 0;

                $error_message .=
                    "You must upload a jpg, jpeg, png, gif, or webp file.<br>";

            } else {

                /* =========================
                   IMAGE UPLOAD PATH
                ========================= */

                $upload_dir =
                    dirname(__DIR__).
                    DIRECTORY_SEPARATOR.
                    'assets'.
                    DIRECTORY_SEPARATOR.
                    'images'.
                    DIRECTORY_SEPARATOR.
                    'blog'.
                    DIRECTORY_SEPARATOR;


                /* Create folder if not exists */

                if (!is_dir($upload_dir)) {

                    if (!mkdir($upload_dir, 0777, true)) {

                        $valid = 0;

                        $error_message .=
                            "Unable to create image upload folder.<br>";
                    }
                }


                /* Check folder */

                if (
                    $valid == 1 &&
                    !is_writable($upload_dir)
                ) {

                    $valid = 0;

                    $error_message .=
                        "Image upload folder is not writable.<br>";
                }


                if ($valid == 1) {

                    /*
                     * Generate new image filename
                     */

                    $final_image =
                        'blog-' .
                        time() .
                        '-' .
                        uniqid() .
                        '.' .
                        $image_ext;


                    $upload_path =
                        $upload_dir .
                        $final_image;


                    if (
                        !move_uploaded_file(
                            $image_tmp,
                            $upload_path
                        )
                    ) {

                        $valid = 0;

                        $error_message .=
                            "Failed to upload image.<br>";

                    } else {

                        /* =========================
                           DELETE OLD IMAGE
                        ========================= */

                        if (!empty($image)) {

                            /*
                             * Supports both:
                             *
                             * blog-xxx.webp
                             *
                             * assets/images/blog/blog-xxx.webp
                             */

                            $old_image_name =
                                basename($image);


                            $old_image_path =
                                $upload_dir .
                                $old_image_name;


                            if (
                                file_exists(
                                    $old_image_path
                                )
                            ) {

                                unlink(
                                    $old_image_path
                                );
                            }
                        }
                    }
                }
            }
        }
    }


    /* =========================
       UPDATE DATABASE
    ========================= */

    if ($valid == 1) {

        try {

            $statement = $pdo->prepare("
                UPDATE blogs SET

                    slug=?,
                    title=?,
                    excerpt=?,
                    content=?,
                    image=?,
                    meta_title=?,
                    meta_keyword=?,
                    meta_description=?,
                    status=?,
                    updated_at=?

                WHERE id=?
            ");


            /*
             * Same image path format as blog-add.php:
             *
             * assets/images/blog/filename.webp
             */

            


            $statement->execute([

                $slug,
                $title,
                $excerpt,
                $content,
                $final_image,
                $meta_title,
                $meta_keyword,
                $meta_description,
                $status,
                date('Y-m-d H:i:s'),
                $current_blog_id

            ]);


            /*
             * Keep current image variable
             * in the same format as database
             */

            $image = $image_path;


            $success_message =
                'Blog updated successfully.';


        } catch (PDOException $e) {

            $error_message =
                'Database Error: ' .
                htmlspecialchars(
                    $e->getMessage(),
                    ENT_QUOTES,
                    'UTF-8'
                );
        }
    }
}

?>


<!-- =========================
     PAGE HEADER
========================= -->

<section class="content-header">

    <div class="content-header-left">

        <h1>Edit Blog</h1>

    </div>


    <div class="content-header-right">

        <a
            href="blog.php"
            class="btn btn-primary btn-sm">

            View All

        </a>

    </div>

</section>


<!-- =========================
     CONTENT
========================= -->

<section class="content">

    <div class="row">

        <div class="col-md-12">


            <!-- ERROR -->

            <?php if (!empty($error_message)): ?>

                <div class="callout callout-danger">

                    <p>

                        <?php
                        echo $error_message;
                        ?>

                    </p>

                </div>

            <?php endif; ?>


            <!-- SUCCESS -->

            <?php if (!empty($success_message)): ?>

                <div class="callout callout-success">

                    <p>

                        <?php
                        echo $success_message;
                        ?>

                    </p>

                </div>

            <?php endif; ?>


            <!-- FORM -->

            <form
                class="form-horizontal"
                action=""
                method="post"
                enctype="multipart/form-data">


                <div class="box box-info">

                    <div class="box-body">


                        <!-- =========================
                             STATUS
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Status

                            </label>


                            <div class="col-sm-4">

                                <select
                                    name="status"
                                    class="form-control select2">

                                    <option
                                        value="1"
                                        <?php
                                        echo ($status == 1)
                                            ? 'selected'
                                            : '';
                                        ?>>

                                        Active

                                    </option>


                                    <option
                                        value="0"
                                        <?php
                                        echo ($status == 0)
                                            ? 'selected'
                                            : '';
                                        ?>>

                                        Deactive

                                    </option>

                                </select>

                            </div>

                        </div>


                        <!-- =========================
                             EXISTING IMAGE
                        ========================== -->

                        <?php if (!empty($image)): ?>

                            <div class="form-group">

                                <label class="col-sm-3 control-label">

                                    Existing Image

                                </label>


                                <div
                                    class="col-sm-9"
                                    style="padding-top:5px">

                                    <img  src="../assets/images/blog/<?php echo $image ?>"
                                        alt="Blog Image"
                                        style="width:400px;max-width:100%;"
                                    >

                                </div>

                            </div>

                        <?php endif; ?>


                        <!-- =========================
                             NEW IMAGE
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Image

                            </label>


                            <div class="col-sm-4">

                                <input
                                    type="file"
                                    class="form-control"
                                    name="image"
                                    accept=".jpg,.jpeg,.png,.gif,.webp"
                                >


                                <small>

                                    JPG, JPEG, PNG, GIF or WEBP

                                </small>

                            </div>

                        </div>


                        <!-- =========================
                             TITLE
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Title

                            </label>


                            <div class="col-sm-6">

                                <input
                                    type="text"
                                    class="form-control"
                                    value="<?php
                                        echo htmlspecialchars(
                                            $title,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        );
                                    ?>"
                                    name="title"
                                >

                            </div>

                        </div>


                        <!-- =========================
                             SHORT DESCRIPTION
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Short Description

                            </label>


                            <div class="col-sm-6">

                                <textarea
                                    class="form-control"
                                    rows="5"
                                    name="excerpt"
                                ><?php
                                    echo htmlspecialchars(
                                        $excerpt,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    );
                                ?></textarea>

                            </div>

                        </div>


                        <!-- =========================
                             CONTENT
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Content

                            </label>


                            <div class="col-sm-8">

                                <textarea
                                    class="form-control"
                                    id="editor1"
                                    cols="30"
                                    rows="15"
                                    name="content"
                                ><?php
                                    echo $content;
                                ?></textarea>

                            </div>

                        </div>


                        <!-- =========================
                             SLUG
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Slug

                            </label>


                            <div class="col-sm-6">

                                <input
                                    type="text"
                                    class="form-control"
                                    value="<?php
                                        echo htmlspecialchars(
                                            $slug,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        );
                                    ?>"
                                    name="slug"
                                >

                            </div>

                        </div>


                        <!-- =========================
                             META TITLE
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Title

                            </label>


                            <div class="col-sm-6">

                                <input
                                    type="text"
                                    class="form-control"
                                    name="meta_title"
                                    placeholder="Top Solar Street Light Manufacturer in India"
                                    value="<?php
                                        echo htmlspecialchars(
                                            $meta_title,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        );
                                    ?>"
                                >

                            </div>

                        </div>


                        <!-- =========================
                             META KEYWORD
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Keyword

                            </label>


                            <div class="col-sm-6">

                                <textarea
                                    class="form-control"
                                    name="meta_keyword"
                                    rows="4"
                                    placeholder="solar street light manufacturer, solar street light, solar lighting system"
                                ><?php
                                    echo htmlspecialchars(
                                        $meta_keyword,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    );
                                ?></textarea>

                            </div>

                        </div>


                        <!-- =========================
                             META DESCRIPTION
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Meta Description

                            </label>


                            <div class="col-sm-6">

                                <textarea
                                    class="form-control"
                                    name="meta_description"
                                    rows="5"
                                    placeholder="Discover reliable solar street light solutions from leading manufacturers in India."
                                ><?php
                                    echo htmlspecialchars(
                                        $meta_description,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    );
                                ?></textarea>

                            </div>

                        </div>


                        <!-- =========================
                             UPDATE BUTTON
                        ========================== -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label"></label>


                            <div class="col-sm-6">

                                <button
                                    type="submit"
                                    class="btn btn-success pull-left"
                                    name="form1">

                                    Update

                                </button>

                            </div>

                        </div>


                    </div>

                </div>


            </form>

        </div>

    </div>

</section>


<?php require_once('footer.php'); ?>