<?php require_once('header.php'); ?>

<?php

$error_message = '';
$success_message = '';

if(isset($_POST['form1'])){

    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $excerpt = trim($_POST['excerpt'] ?? '');
    $content = trim($_POST['content'] ?? '');

    $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 UPLOAD
    ========================= */

    $final_name = '';

    if(
        isset($_FILES['image']) &&
        $_FILES['image']['error'] != UPLOAD_ERR_NO_FILE
    ){

        $path = $_FILES['image']['name'];
        $path_tmp = $_FILES['image']['tmp_name'];
        $file_error = $_FILES['image']['error'];

        if($file_error != UPLOAD_ERR_OK){

            $valid = 0;

            $error_message .=
                'There was an error uploading the image.<br>';

        }else{

            $ext = strtolower(
                pathinfo($path, PATHINFO_EXTENSION)
            );

            $allowed_extensions = [
                'jpg',
                'jpeg',
                'png',
                'gif',
                'webp'
            ];

            if(!in_array($ext, $allowed_extensions, true)){

                $valid = 0;

                $error_message .=
                    'You must upload a jpg, jpeg, png, gif or webp file.<br>';

            }else{

                $upload_dir =
                    dirname(__DIR__).
                    DIRECTORY_SEPARATOR.
                    'assets'.
                    DIRECTORY_SEPARATOR.
                    'images'.
                    DIRECTORY_SEPARATOR.
                    'blog'.
                    DIRECTORY_SEPARATOR;


                if(!is_dir($upload_dir)){

                    if(!mkdir($upload_dir, 0777, true)){

                        $valid = 0;

                        $error_message .=
                            'Unable to create image upload folder.<br>';
                    }
                }


                if(
                    $valid == 1 &&
                    !is_writable($upload_dir)
                ){

                    $valid = 0;

                    $error_message .=
                        'Image upload folder is not writable.<br>';
                }


                if($valid == 1){

                    $final_name =
                        'blog-'.
                        time().
                        '-'.
                        uniqid().
                        '.'.
                        $ext;


                    $upload_path =
                        $upload_dir.$final_name;


                    if(
                        !move_uploaded_file(
                            $path_tmp,
                            $upload_path
                        )
                    ){

                        $valid = 0;

                        $final_name = '';

                        $error_message .=
                            'Failed to move uploaded image.<br>';
                    }
                }
            }
        }
    }


    /* =========================
       SAVE DATA
    ========================= */

    if($valid == 1){

        try{

            $statement = $pdo->prepare("
                INSERT INTO blogs
                (
                    slug,
                    title,
                    excerpt,
                    content,
                    image,
                    meta_title,
                    meta_keyword,
                    meta_description,
                    status,
                    created_at,
                    updated_at
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    NOW(),
                    NOW()
                )
            ");


            

            $statement->execute([

                $slug,
                $title,
                $excerpt,
                $content,
                $final_name,
                $meta_title,
                $meta_keyword,
                $meta_description,
                $status

            ]);


            $success_message =
                'Blog is added successfully.';


            /* =========================
               RESET FORM
            ========================= */

            $_POST['title'] = '';
            $_POST['slug'] = '';
            $_POST['excerpt'] = '';
            $_POST['content'] = '';

            $_POST['meta_title'] = '';
            $_POST['meta_keyword'] = '';
            $_POST['meta_description'] = '';

            $_POST['status'] = 1;


        }catch(PDOException $e){

            /* Delete uploaded image if DB insert fails */

            if($final_name != ''){

                $uploaded_file =
                    dirname(__DIR__).
                    DIRECTORY_SEPARATOR.
                    'assets'.
                    DIRECTORY_SEPARATOR.
                    'images'.
                    DIRECTORY_SEPARATOR.
                    'blog'.
                    DIRECTORY_SEPARATOR.
                    $final_name;


                if(file_exists($uploaded_file)){

                    unlink($uploaded_file);
                }
            }


            $error_message =
                'Database Error: '.
                htmlspecialchars(
                    $e->getMessage(),
                    ENT_QUOTES,
                    'UTF-8'
                );
        }
    }
}

?>


<section class="content-header">

    <div class="content-header-left">

        <h1>Add Blog</h1>

    </div>


    <div class="content-header-right">

        <a
            href="blog.php"
            class="btn btn-primary btn-sm">

            View All

        </a>

    </div>

</section>


<section class="content">

    <div class="row">

        <div class="col-md-12">


            <?php if(!empty($error_message)): ?>

                <div class="callout callout-danger">

                    <p>
                        <?php echo $error_message; ?>
                    </p>

                </div>

            <?php endif; ?>


            <?php if(!empty($success_message)): ?>

                <div class="callout callout-success">

                    <p>
                        <?php echo $success_message; ?>
                    </p>

                </div>

            <?php endif; ?>


            <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">

                                    <option
                                        value="1"
                                        <?php echo (
                                            ($_POST['status'] ?? 1) == 1
                                        ) ? 'selected' : ''; ?>>

                                        Active

                                    </option>


                                    <option
                                        value="0"
                                        <?php echo (
                                            ($_POST['status'] ?? 1) == 0
                                        ) ? 'selected' : ''; ?>>

                                        Deactive

                                    </option>

                                </select>

                            </div>

                        </div>


                        <!-- BLOG IMAGE -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Blog 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"
                                    name="title"
                                    placeholder="Modern Industrial Surface Treatment Solutions"
                                    value="<?php
                                        echo isset($_POST['title'])
                                            ? htmlspecialchars(
                                                $_POST['title'],
                                                ENT_QUOTES,
                                                'UTF-8'
                                            )
                                            : '';
                                    ?>">

                            </div>

                        </div>


                        <!-- EXCERPT -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label">

                                Short Description

                            </label>


                            <div class="col-sm-6">

                                <textarea
                                    class="form-control"
                                    rows="4"
                                    name="excerpt"
                                    placeholder="Discover how modern surface treatment systems improve product quality, durability and production efficiency."><?php
                                        echo isset($_POST['excerpt'])
                                            ? htmlspecialchars(
                                                $_POST['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 isset($_POST['content'])
                                            ? $_POST['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"
                                    name="slug"
                                    placeholder="modern-industrial-surface-treatment-solutions"
                                    value="<?php
                                        echo isset($_POST['slug'])
                                            ? htmlspecialchars(
                                                $_POST['slug'],
                                                ENT_QUOTES,
                                                'UTF-8'
                                            )
                                            : '';
                                    ?>">

                            </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 isset($_POST['meta_title'])
                                            ? htmlspecialchars(
                                                $_POST['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 isset($_POST['meta_keyword'])
                                            ? htmlspecialchars(
                                                $_POST['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 isset($_POST['meta_description'])
                                            ? htmlspecialchars(
                                                $_POST['meta_description'],
                                                ENT_QUOTES,
                                                'UTF-8'
                                            )
                                            : '';
                                    ?></textarea>

                            </div>

                        </div>


                        <!-- SUBMIT -->

                        <div class="form-group">

                            <label class="col-sm-3 control-label"></label>


                            <div class="col-sm-6">

                                <button
                                    type="submit"
                                    class="btn btn-success"
                                    name="form1"
                                    value="1">

                                    Submit

                                </button>

                            </div>

                        </div>


                    </div>

                </div>


            </form>


        </div>

    </div>

</section>


<?php require_once('footer.php'); ?>