<?php
/**
 * home-sliders.php -- Home Sliders
 */

include '../inc/config.inc.php'; // Configuration

ob_start();
session_start();

//date_default_timezone_set('Africa/Lagos');

error_reporting(E_ALL);
ini_set('display_errors', 1);

if ( !isset($_SESSION['admin']) || $_SESSION["loggedin"] !== true || trim($_SESSION['admin']) == '' ){
	//header('Location: ' . $BASE_URL . 'wp-admin/');
    header('Location: ' . $BASE_URL . 'signin');
	exit;
}

?>

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Home Sliders - Alert Signals Nation</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="../img/Signals-Alert-3.png" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">

    <script src="../plugins/sweetalerts/promise-polyfill.js"></script>
    <link href="../plugins/sweetalerts/sweetalert.css" rel="stylesheet" type="text/css" />

    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600,700" rel="stylesheet" />
    <style>
        /*------ Google Font Style ------ */
        body {font-family:'Roboto'!important;}
    </style>

</head>
<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php include 'navbar.php' ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between">
                                <div class="iq-header-title">
                                    <h4 class="card-title" style="font-family: 'Roboto'!important;">Home Sliders</h4>
                                </div>
                            </div>
                            <div class="iq-card-body">

                                <?php
                                if ( isset($_GET['edit'], $_GET['id']) ){
                                    $slider_id = intval($_GET['id']);
                                    $getSlider = $db_con->query("SELECT * FROM home_sliders WHERE slider_id='$slider_id'");
                                    $sliderRow = $getSlider->fetch(PDO::FETCH_ASSOC);
                                ?>
                                    <form action="" method="post" enctype="multipart/form-data">
                                        <div class="col-sm-12 col-md-6">
                                            <div class="form-group col-sm-12">
                                                <label>Slider Title:</label>
                                                <input type="text" class="form-control" name="slider_title" value="<?= $sliderRow['slider_title']; ?>">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Slider Description:</label>
                                                <input type="text" class="form-control" name="slider_description" value="<?= $sliderRow['slider_description']; ?>">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Slider Image:</label>
                                                <input type="file" class="form-control" name="sliderImg" accept="image/*" required>
                                            </div>

                                            <div class="form-group col-sm-6">
                                                <button type="submit" name="update_slider" class="btn btn-primary float-right" value="Submit">Update</button>
                                            </div><br>
                                        </div>
                                    </form>
                                    <?php
                                    if ( isset($_POST['update_slider']) ){
                                        error_reporting(E_ALL);

                                        $slider_title = strip_tags(addslashes($_POST['slider_title']));
                                        $slider_description = strip_tags(addslashes($_POST['slider_description']));

                                        $targetDir = "uploads/"; // Directory to save in uploads
                                        $allowedExts = array('jpg', 'jpeg', 'png'); // Allowed File Types

                                        if ( !empty($_FILES['sliderImg']['name']) ){
                                            $uploads = $db_con->prepare("SELECT file FROM home_sliders WHERE slider_id='".$sliderRow['slider_id']."'");
                                            $uploads->execute();
                                            $get = $uploads->fetch(PDO::FETCH_ASSOC);

                                            $extSlider = pathinfo(basename($_FILES['sliderImg']['name']), PATHINFO_EXTENSION); // Get the extension
                                            if ( !in_array(strtolower($extSlider), $allowedExts) ){
                                    ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Invalid File Type. Upload an Image.', 'error');
                                                    }, 2000);
                                                </script>
                                    <?php
                                            } else {
                                                $newSlider = 'slider_' . randDoc($extSlider); // Randomization

                                                if ( (file_exists($targetDir . $get['file']) AND !empty($get['file'])) ){
                                                    unlink($targetDir . $get['file']); // Delete Old File
                                                }
                                                
                                                $query = $db_con->prepare("UPDATE home_sliders SET slider_title='$slider_title', slider_description='$slider_description', file='$newSlider' WHERE slider_id='".$sliderRow['slider_id']."'");
                                                
                                                if ( move_uploaded_file($_FILES['sliderImg']['tmp_name'], $targetDir . $newSlider) ){
                                                    $query->execute();
                                    ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Slider Updated & Image Uploaded', 'success');
                                                        }, 2000);
                                                    </script>
                                    <?php
                                                } else {
                                    ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Something Went Wrong. Try again.', 'error');
                                                        }, 2000);
                                                    </script>
                                    <?php
                                                }
                                            }
                                        } else {
                                            $query = $db_con->prepare("UPDATE home_sliders SET slider_title='$slider_title', slider_description='$slider_description' WHERE slider_id='".$sliderRow['slider_id']."'");

                                            if ( $query->execute() ){
                                    ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Slider Updated', 'success');
                                                    }, 2000);
                                                </script>
                                    <?php
                                            } else {
                                    ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Something Went Wrong. Try again.', 'error');
                                                    }, 2000);
                                                </script>
                                    <?php
                                            }
                                        }
                                    }
                                    ?>
                                <?php
                                } else {
                                ?>
                                    <form action="" method="post" enctype="multipart/form-data">
                                        <div class="col-sm-12 col-md-6">
                                            <div class="form-group col-sm-12">
                                                <label>Slider Title:</label>
                                                <input type="text" class="form-control" name="slider_title">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Slider Description:</label>
                                                <input type="text" class="form-control" name="slider_description">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Slider Image:</label>
                                                <input type="file" class="form-control" name="sliderImg" accept="image/*" required>
                                            </div>

                                            <div class="form-group col-sm-6">
                                                <button type="submit" name="upload_slider" class="btn btn-primary float-right" value="Submit">Submit</button>
                                            </div>
                                        </div>
                                    </form><br>
                                    <hr style="border-top:1px solid #000;">
                                <?php
                                    if ( isset($_POST['upload_slider']) ){
                                        error_reporting(E_ALL);

                                        $slider_title = strip_tags(addslashes($_POST['slider_title']));
                                        $slider_description = strip_tags(addslashes($_POST['slider_description']));
                                        $created = date('Y-m-d H:i:s');

                                        $targetDir = "uploads/"; // Directory to save in uploads
                                        $allowedExts = array('jpg', 'jpeg', 'png'); // Allowed File Types

                                        if ( !empty($_FILES['sliderImg']['name']) ){
                                            $extSlider = pathinfo(basename($_FILES['sliderImg']['name']), PATHINFO_EXTENSION); // Get the extension
                                            if ( !in_array(strtolower($extSlider), $allowedExts) ){
                                ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Invalid File Type. Upload an Image.', 'error');
                                                    }, 2000);
                                                </script>
                                <?php
                                            } else {
                                                $newSlider = 'slider_' . randDoc($extSlider); // Randomization
                                                
                                                $insert = "INSERT INTO home_sliders(slider_title, slider_description, file, created) VALUES ('$slider_title', '$slider_description', '$newSlider', '$created')";
                                                
                                                if ( move_uploaded_file($_FILES['sliderImg']['tmp_name'], $targetDir . $newSlider) ){
                                                    $db_con->exec($insert);
                                ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Slider Added', 'success');
                                                        }, 2000);
                                                    </script>
                                <?php
                                                } else {
                                ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Something Went Wrong. Try again.', 'error');
                                                        }, 2000);
                                                    </script>
                                <?php
                                                }
                                            }
                                        } else {
                                ?>
                                            <script>
                                                setTimeout(function(){
                                                    noticePop('Slider Image Must Be Selected for Upload.', 'error');
                                                }, 2000);
                                            </script>
                                <?php
                                        }
                                    }
                                ?>

                                    <div class="table-responsive">
                                        <div class="row justify-content-between">
                                            <div class="col-sm-12 col-md-6">
                                                <div id="user_list_datatable_info" class="dataTables_filter">
                                                    <form class="mr-3 position-relative">
                                                        <div class="form-group mb-0">
                                                            <input type="search" class="form-control" id="exampleInputSearch" placeholder="Search" aria-controls="user-list-table">
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                        <table id="user-list-table" class="table table-striped table-bordered mt-4" role="grid" aria-describedby="user-list-page-info">
                                            <thead>
                                                <tr>
                                                    <th>Title</th>
                                                    <th>Description</th>
                                                    <th>Image</th>
                                                    <th>Created</th>
                                                    <th>Published?</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            <?php
                                            // Sliders
                                            $sliders = $db_con->prepare("SELECT * FROM home_sliders ORDER BY created ASC");

                                            if ( $sliders->execute() ){
                                                $i = 0;
                                                while ( $slider = $sliders->fetch(PDO::FETCH_ASSOC) ){
                                                    $i++;
                                            ?>
                                                    <tr>
                                                        <td><?= $slider['slider_title']; ?></td>
                                                        <td><?= $slider['slider_description']; ?></td>
                                                        <td class="text-center">
                                                            <img class="rounded img-fluid avatar-40" src="uploads/<?= $slider['file']; ?>" alt="slider">
                                                        </td>
                                                        <td><?= date('Y/m/d', strtotime($slider['created'])); ?></td>
                                                        <td class="text-center">
                                                            <button class="btn btn-sm btn-primary" type="button" onclick="PublishSlider('Yes', <?= $slider['slider_id']; ?>)" <? if ($slider['publish']=='Yes') echo 'disabled'; ?>>Yes</button>
                                                            <button class="btn btn-sm btn-primary" type="button" onclick="PublishSlider('No', <?= $slider['slider_id']; ?>)" <? if ($slider['publish']=='No') echo 'disabled'; ?>>No</button>
                                                        </td>
                                                        <td class="text-center">
                                                            <div class="d-flex align-items-center list-user-action">
                                                                <a class="iq-bg-primary" data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit" href="?edit&id=<?= $slider['slider_id']; ?>"><i class="ri-pencil-line"></i></a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                            <?php
                                                }
                                            }
                                            ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <?php include 'footer.php' ?>
    <!-- color-customizer END -->
    <!-- Optional JavaScript -->
    <script src="../plugins/jquery-3.1.1.min.js"></script>
    <script src="../plugins/sweetalerts/sweetalert2.min.js"></script>
    <script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.js"></script>

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <!--<script src="js/jquery.min.js"></script>
    <script src="js/popper.min.js"></script>-->
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- am core JavaScript -->
    <script src="js/core.js"></script>
    <!-- am charts JavaScript -->
    <script src="js/charts.js"></script>
    <!-- am animated JavaScript -->
    <script src="js/animated.js"></script>
    <!-- am kelly JavaScript -->
    <script src="js/kelly.js"></script>
    <!-- am maps JavaScript -->
    <script src="js/maps.js"></script>
    <!-- am worldLow JavaScript -->
    <script src="js/worldLow.js"></script>
    <!-- Style Customizer -->
    <script src="js/style-customizer.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>

    <script>
        // BASE URL and API Inclusion
        const BASE_URL = '<?= $BASE_URL; ?>';
        const API = `${BASE_URL}api/admin.php`;

        function noticePop(value, type) {
            swal({
                html: '<span style="font-size:18px!important;">' + `${value}` + '</span>',
                type: `${type}`,
                timer: 4000,
                showConfirmButton: false,
                allowOutsideClick: false,
                allowEscapeKey: false,
            }).then(function() {
                window.location.href = 'home-sliders';
            });
        }

        function PublishSlider( action_type, sid ){
            $.ajax({
                url: API,
                type: 'POST',
                //dataType: 'JSON',
                data: {
                    publish_slider: 'publish_slider',
                    action_type: action_type,
                    slider_id: sid
                },
                cache: false
            }).done( function( result ){
                if ( result.error == false && result.notice == 'changed' ){
                    noticePop( result.message, 'success' );
                }
                else if ( result.error == true && result.notice == 'failed' ){
                    noticePop( result.message, 'error' );
                }
            });
        }
    </script>

</body>
</html>