<?php
/**
 * home-testimonials.php -- Home Testimonials
 */

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 Testimonials - 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 Testimonies</h4>
                                </div>
                            </div>
                            <div class="iq-card-body">

                                <?php
                                if ( isset($_GET['edit'], $_GET['id']) ){
                                    $testimony_id = intval($_GET['id']);
                                    $getTestimony = $db_con->query("SELECT * FROM home_testimonials WHERE testimony_id='$testimony_id'");
                                    $testimonyRow = $getTestimony->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>Name:</label>
                                                <input type="text" class="form-control" name="name" value="<?= $testimonyRow['name']; ?>">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Position:</label>
                                                <input type="text" class="form-control" name="position" value="<?= $testimonyRow['position']; ?>">
                                            </div>

                                            <div class="form-group col-sm-12">
                                                <label>Testimony:</label>
                                                <textarea class="form-control" name="testimony"><?= $testimonyRow['testimony']; ?></textarea>
                                            </div>

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

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

                                        $name = strip_tags($_POST['name']);
                                        $position = strip_tags(addslashes($_POST['position']));
                                        $testimony = strip_tags(addslashes($_POST['testimony']));

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

                                        if ( !empty($_FILES['testImg']['name']) ){
                                            $uploads = $db_con->prepare("SELECT file FROM home_testimonials WHERE testimony_id='".$testimonyRow['testimony_id']."'");
                                            $uploads->execute();
                                            $get = $uploads->fetch(PDO::FETCH_ASSOC);

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

                                                if ( (file_exists($targetDir . $get['file']) AND !empty($get['file'])) ){
                                                    unlink($targetDir . $get['file']); // Delete Old File
                                                }
                                                
                                                $query = $db_con->prepare("UPDATE home_testimonials SET name='$name', position='$position', testimony='$testimony', file='$newTestimony' WHERE testimony_id='".$testimonyRow['testimony_id']."'");
                                                
                                                if ( move_uploaded_file($_FILES['testImg']['tmp_name'], $targetDir . $newTestimony) ){
                                                    $query->execute();
                                    ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Testimonial 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_testimonials SET name='$name', position='$position', testimony='$testimony' WHERE testimony_id='".$testimonyRow['testimony_id']."'");

                                            if ( $query->execute() ){
                                    ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Testimonial 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>Name:</label>
                                                <input type="text" class="form-control" name="name">
                                            </div>

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

                                            <div class="form-group col-sm-12">
                                                <label>Testimony:</label>
                                                <textarea class="form-control" name="testimony"></textarea>
                                            </div>

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

                                            <div class="form-group col-sm-6">
                                                <button type="submit" name="upload_testimony" 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_testimony']) ){
                                        error_reporting(E_ALL);

                                        $name = strip_tags($_POST['name']);
                                        $position = strip_tags(addslashes($_POST['position']));
                                        $testimony = strip_tags(addslashes($_POST['testimony']));
                                        $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['testImg']['name']) ){
                                            $extTestimony = pathinfo(basename($_FILES['testImg']['name']), PATHINFO_EXTENSION); // Get the extension
                                            if ( !in_array(strtolower($extTestimony), $allowedExts) ){
                                ?>
                                                <script>
                                                    setTimeout(function(){
                                                        noticePop('Invalid File Type. Upload an Image.', 'error');
                                                    }, 2000);
                                                </script>
                                <?php
                                            } else {
                                                $newTestimony = 'testimony_' . randDoc($extTestimony); // Randomization
                                                
                                                $insert = "INSERT INTO home_testimonials(name, position, testimony, file, created) VALUES ('$name', '$position', '$testimony', '$newTestimony', '$created')";
                                                
                                                if ( move_uploaded_file($_FILES['testImg']['tmp_name'], $targetDir . $newTestimony) ){
                                                    $db_con->exec($insert);
                                ?>
                                                    <script>
                                                        setTimeout(function(){
                                                            noticePop('Testimony 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>Name</th>
                                                    <th>Position</th>
                                                    <th>Testimony</th>
                                                    <th>Image</th>
                                                    <th>Created</th>
                                                    <th>Published?</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            <?php
                                            // Testimonials
                                            $testimonials = $db_con->prepare("SELECT * FROM home_testimonials ORDER BY created ASC");

                                            if ( $testimonials->execute() ){
                                                $i = 0;
                                                while ( $testimony = $testimonials->fetch(PDO::FETCH_ASSOC) ){
                                                    $i++;
                                            ?>
                                                    <tr>
                                                        <td><?= $testimony['name']; ?></td>
                                                        <td><?= $testimony['position']; ?></td>
                                                        <td><?= $testimony['testimony']; ?></td>
                                                        <td class="text-center">
                                                            <img class="rounded img-fluid avatar-40" src="uploads/<?= $testimony['file']; ?>" alt="testimony">
                                                        </td>
                                                        <td><?= date('Y/m/d', strtotime($testimony['created'])); ?></td>
                                                        <td class="text-center">
                                                            <button class="btn btn-sm btn-primary" type="button" onclick="PublishTestimony('Yes', <?= $testimony['testimony_id']; ?>)" <? if ($testimony['publish']=='Yes') echo 'disabled'; ?>>Yes</button>
                                                            <button class="btn btn-sm btn-primary" type="button" onclick="PublishTestimony('No', <?= $testimony['testimony_id']; ?>)" <? if ($testimony['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=<?= $testimony['testimony_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-testimonials';
            });
        }

        function PublishTestimony( action_type, tid ){
            $.ajax({
                url: API,
                type: 'POST',
                //dataType: 'JSON',
                data: {
                    publish_testimony: 'publish_testimony',
                    action_type: action_type,
                    testimony_id: tid
                },
                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>