<?php
include("includes/header.php");
$page_title = "Manage Subscription";
$add_page_title = "Add Subscription";

$_GET = validate_input($_GET);
$tableName = "tbl_subscription";
$targetpage = "manage_subscription.php";
$limit = 10;

$searchInput = $_GET['keyword'];
if ($searchInput != "") {
    $query = "SELECT COUNT(*) as num FROM tbl_subscription WHERE tbl_subscription.`plan_name` LIKE '%$searchInput%' 
    OR tbl_subscription.`plan_duration` LIKE '%$searchInput%' OR tbl_subscription.`plan_price` LIKE '%$searchInput%' 
    OR tbl_subscription.`playstore_id` LIKE '%$searchInput%' OR tbl_subscription.`appstore_id` LIKE '%$searchInput%'";
    $total_pages = mysqli_fetch_array(mysqli_query($mysqli, $query));
    $total_pages = $total_pages['num'];
} else {
    $query = "SELECT COUNT(*) as num FROM $tableName";
    $total_pages = mysqli_fetch_array(mysqli_query($mysqli, $query));
    $total_pages = $total_pages['num'];
}

$stages = 3;
$page = 0;
if (isset($_GET['page'])) {
    $page = mysqli_real_escape_string($mysqli, $_GET['page']);
}
if ($page) {
    $start = ($page - 1) * $limit;
} else {
    $start = 0;
}

if ($searchInput != "") {
    $sql_query = "SELECT * FROM tbl_subscription WHERE tbl_subscription.`plan_name` LIKE '%$searchInput%' 
    OR tbl_subscription.`plan_duration` LIKE '%$searchInput%' OR tbl_subscription.`plan_price` LIKE '%$searchInput%' 
    OR tbl_subscription.`playstore_id` LIKE '%$searchInput%' OR tbl_subscription.`appstore_id` LIKE '%$searchInput%' 
    ORDER BY tbl_subscription.`id` DESC LIMIT $start, $limit";
    $result = mysqli_query($mysqli, $sql_query) or die(mysqli_error($mysqli));
} else {
    $sql_query = "SELECT * FROM tbl_subscription ORDER BY tbl_subscription.`id` DESC LIMIT $start, $limit";
    $result = mysqli_query($mysqli, $sql_query) or die(mysqli_error($mysqli));
}
?>
<main id="main" class="main">
    <div class="row">
        <div class="col-lg-3">
            <div class="pagetitle">
                <h1><?php _e($page_title); ?></h1>
            </div>
        </div>
        <div class="col-lg-6">
            <form method="get" id="searchForm" action="">
                <input class="form-control input-sm" placeholder="Search here..." aria-controls="DataTables_Table_0" type="search" name="keyword" value="<?php if (isset($_GET['keyword'])) {
                                                                                                                                                                _e($_GET['keyword']);
                                                                                                                                                            } ?>" required="required">
            </form>
        </div>
        <div class="col-lg-3 float-right">
            <div class="d-flex justify-content-end">
                <a href="add_subscription.php?add=yes">
                    <button type="button" class="btn btn-outline-primary btn-lg"><?php _e($add_page_title); ?></button>
                </a>
            </div>
        </div>
    </div><br>
    <div class="row">
        <div class="col-xl-12 col-xxl-12 col-lg-12 col-md-12 col-sm-12" style="display: flex; justify-content: flex-end;">
            <div style="margin-top: 8px;">
                <input type="checkbox" id="checkall_input">
                <label for="checkall_input">Select All</label>
            </div>
            <div class="dropdown" style="margin-left: 6px;">
                <button class="btn btn-primary dropdown-toggle btn_cust" type="button" data-toggle="dropdown">Action
                    <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <li style=" text-align: center;"><a href="" class="actions" data-action="enable">Enable</a></li>
                    <li style=" text-align: center;"><a href="" class="actions" data-action="disable">Disable</a></li>
                    <li style=" text-align: center;"><a href="" class="actions" data-action="delete">Delete</a></li>
                </ul>
            </div>
        </div>
    </div>
    <section class="section">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Duration</th>
                                        <th>Price</th>
                                        <th>Play Store Id</th>
                                        <th>App Store Id</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $i = 0;
                                    while ($row = mysqli_fetch_assoc($result)) {
                                    ?>
                                        <tr>
                                            <td scope="row">
                                                <input type="checkbox" name="post_ids[]" id="checkbox<?php _e($i); ?>" value="<?php _e($row['id']); ?>" class="post_ids">
                                            </td>
                                            <td><?php _e($row['plan_name']); ?></td>
                                            <td><?php echo $row['plan_duration'] . ' ' . $row['plan_type']; ?></td>
                                            <td><?php _e($row['plan_price']); ?></td>
                                            <td><?php _e($row['playstore_id']); ?></td>
                                            <td><?php _e($row['appstore_id']); ?></td>
                                            <td>
                                                <?php if ($row['status'] != "0") { ?>
                                                    <a title="Change Status" class="toggle_btn_a" href="javascript:void(0)" data-id="<?php _e($row['id']); ?>" data-action="deactive" data-column="status"><span class="btn btn-primary"><i class="fa fa-check" aria-hidden="true"></i><span>Enable</span></span></a>

                                                <?php } else { ?>
                                                    <a title="Change Status" class="toggle_btn_a" href="javascript:void(0)" data-id="<?php _e($row['id']); ?>" data-action="active" data-column="status"><span class="btn btn-danger"><i class="fa fa-check" aria-hidden="true"></i><span>Disable </span></span></a>
                                                <?php } ?>
                                            </td>
                                            <td>
                                                <a href="add_subscription.php?subscription_id=<?php _e($row['id']); ?>" class="btn btn-primary">
                                                    <i class="bi bi-pencil-square"></i>
                                                </a>
                                                <a href="javascript:void(0)" data-id="<?php _e($row['id']); ?>" class="btn btn-danger btn_delete_a btn_cust" data-toggle="tooltip" data-tooltip="Delete !">
                                                    <i class="bi bi-trash-fill"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php
                                    }
                                    ?>
                                </tbody>
                            </table>
                            <!-- End Table with stripped rows -->
                        </div>
                    </div>
                    <div class="col-md-12 col-xs-12 d-flex justify-content-end paginationRight">
                        <nav aria-label="Page navigation example">
                            <?php
                            include("pagination.php");
                            ?>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </section>
    </div>
    <script type="text/javascript">
        $(".btn_show_rate").click(function(e) {
            $("#ratingModal .modal-title").text($(this).data("title"));
            $("#ratingModal .modal-body").html($(this).next(".rating_container").html());

            $("#ratingModal").modal("show");

        });

        $(".toggle_btn_a").on("click", function(e) {
            e.preventDefault();
            var _for = $(this).data("action");
            var _id = $(this).data("id");
            var _column = $(this).data("column");
            var _table = 'tbl_subscription';

            $.ajax({
                type: 'post',
                url: 'processdata.php',
                dataType: 'json',
                data: {
                    id: _id,
                    for_action: _for,
                    column: _column,
                    table: _table,
                    'action': 'toggle_status',
                    'tbl_id': 'id'
                },
                success: function(res) {
                    console.log(res);
                    if (res.status == '1') {
                        location.reload();
                    }
                }
            });

        });

        $(".btn_delete_a").click(function(e) {

            e.preventDefault();

            var _id = $(this).data("id");
            var _table = 'tbl_subscription';

            swal({
                    title: "Are you sure?\nAll data will be deleted of this subscription.",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger btn_edit",
                    cancelButtonClass: "btn-warning btn_edit",
                    confirmButtonText: "Yes",
                    cancelButtonText: "No",
                    closeOnConfirm: false,
                    closeOnCancel: false,
                    showLoaderOnConfirm: true
                },
                function(isConfirm) {
                    if (isConfirm) {

                        $.ajax({
                            type: 'post',
                            url: 'processdata.php',
                            dataType: 'json',
                            data: {
                                id: _id,
                                tbl_nm: _table,
                                'action': 'multi_delete'
                            },
                            success: function(res) {
                                console.log(res);
                                if (res.status == '1') {
                                    swal({
                                        title: "Successfully",
                                        text: "Subscription is deleted...",
                                        type: "success"
                                    }, function() {
                                        location.reload();
                                    });
                                }
                            }
                        });
                    } else {
                        swal.close();
                    }
                });
        });
        $(".actions").click(function(e) {
            e.preventDefault();

            var _ids = $.map($('.post_ids:checked'), function(c) {
                return c.value;
            });
            var _action = $(this).data("action");

            if (_ids != '') {
                swal({
                        title: "Do you really want to perform?",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonClass: "btn-danger btn_edit",
                        cancelButtonClass: "btn-warning btn_edit",
                        confirmButtonText: "Yes",
                        cancelButtonText: "No",
                        closeOnConfirm: false,
                        closeOnCancel: false,
                        showLoaderOnConfirm: true
                    },
                    function(isConfirm) {
                        if (isConfirm) {

                            var _table = 'tbl_subscription';

                            $.ajax({
                                type: 'post',
                                url: 'processdata.php',
                                dataType: 'json',
                                data: {
                                    id: _ids,
                                    for_action: _action,
                                    table: _table,
                                    'action': 'multi_action'
                                },
                                success: function(res) {
                                    console.log(res);
                                    $('.notifyjs-corner').empty();
                                    if (res.status == '1') {
                                        swal({
                                            title: "Successfully",
                                            text: "You have successfully done",
                                            type: "success"
                                        }, function() {
                                            location.reload();
                                        });
                                    }
                                }
                            });
                        } else {
                            swal.close();
                        }

                    });
            } else {
                swal("Sorry no episode selected !!")
            }
        });

        $(".filter").on("change", function(e) {
            $("#filterForm *").filter(":input").each(function() {
                if ($(this).val() == '')
                    $(this).prop("disabled", true);
            });
            $("#filterForm").submit();
        });


        var totalItems = 0;

        $("#checkall_input").click(function() {

            totalItems = 0;

            $('input:checkbox').not(this).prop('checked', this.checked);
            $.each($("input[name='post_ids[]']:checked"), function() {
                totalItems = totalItems + 1;
            });

            if ($('input:checkbox').prop("checked") == true) {
                $('.notifyjs-corner').empty();
                $.notify(
                    'Total ' + totalItems + ' item checked', {
                        position: "top center",
                        className: 'success'
                    }
                );
            } else if ($('input:checkbox').prop("checked") == false) {
                totalItems = 0;
                $('.notifyjs-corner').empty();
            }
        });

        var noteOption = {
            clickToHide: false,
            autoHide: false,
        }

        $.notify.defaults(noteOption);

        $(".post_ids").click(function(e) {

            if ($(this).prop("checked") == true) {
                totalItems = totalItems + 1;
            } else if ($(this).prop("checked") == false) {
                totalItems = totalItems - 1;
            }

            if (totalItems == 0) {
                $('.notifyjs-corner').empty();
                exit();
            }

            $('.notifyjs-corner').empty();

            $.notify(
                'Total ' + totalItems + ' item checked', {
                    position: "top center",
                    className: 'success'
                }
            );


        });
    </script>
</main>
<?php include("includes/footer.php"); ?>