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

$_GET = validate_input($_GET);
$tableName = "tbl_iteams";
$targetpage = "manage_album.php";
$limit = 10;

$searchInput = isset($_GET['keyword']) ? $_GET['keyword'] : '';
$caregory = isset($_GET['category']) ? $_GET['category'] : '';

$whereClause = "";

if ($caregory != "") {
    if ($caregory != "") {
        $whereClause .= " FIND_IN_SET('$caregory', tbl_category.cid)";
    }
}

if (!empty($searchInput)) {
    if (!empty($whereClause)) {
        $whereClause .= " AND ";
    }
    $whereClause .= "(tbl_iteams.iteam_name LIKE '%$searchInput%' OR tbl_category.category_name LIKE '%$searchInput%')";
}

if (!empty($whereClause)) {
    $query = "SELECT COUNT(*) as num FROM tbl_iteams LEFT JOIN tbl_category ON tbl_iteams.cat_id = tbl_category.cid WHERE $whereClause";
} 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 = isset($_GET['page']) ? mysqli_real_escape_string($mysqli, $_GET['page']) : 0;
$start = ($page > 0) ? ($page - 1) * $limit : 0;

if (!empty($whereClause)) {
    $sql_query = "SELECT tbl_category.category_name, tbl_iteams.* FROM tbl_iteams LEFT JOIN tbl_category ON tbl_category.cid = tbl_iteams.cat_id WHERE $whereClause ORDER BY tbl_iteams.itemid  DESC LIMIT $start, $limit";
} else {
    $sql_query = "SELECT tbl_category.category_name, tbl_iteams.* FROM tbl_iteams LEFT JOIN tbl_category ON tbl_category.cid = tbl_iteams.cat_id ORDER BY tbl_iteams.itemid  DESC LIMIT $start, $limit";
}

$result = mysqli_query($mysqli, $sql_query);
if (!$result) {
    die("Error in SQL query: " . mysqli_error($mysqli));
}

$cat_qry = "SELECT * FROM tbl_category";
$cat_result = mysqli_query($mysqli, $cat_qry);
if (!$cat_result) {
    die("Error in SQL query: " . mysqli_error($mysqli));
}
$categories = array();
while ($row = mysqli_fetch_array($cat_result)) {
    $categories[$row['cid']] = $row['category_name'];
}
?>
<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_album.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-8 col-xxl-8 col-lg-8 col-md-8 col-sm-12">
            <h4 style="float: left;margin-top: 10px;">Filter :-</h4>
            <form id="filterForm" accept="" method="GET" style="display: flex;">
                <div class="col-md-3">
                    <div class="" style="padding: 0px 0px 5px;">
                        <select name="category" class="form-control select2 filter" style="padding: 5px 10px;height: 40px;">
                            <option value="">All Category</option>
                            <?php
                            $sql_cat = "SELECT * FROM tbl_category ORDER BY tbl_category.cid DESC";
                            $res_cat = mysqli_query($mysqli, $sql_cat);
                            while ($row_cat = mysqli_fetch_array($res_cat)) {
                            ?>
                                <option value="<?php echo $row_cat['cid']; ?>" <?php if (isset($_GET['category']) && $_GET['category'] == $row_cat['cid']) {
                                                                                    echo 'selected';
                                                                                } ?> style="background-image:url('images/31295_2.png');"><?php echo $row_cat['category_name']; ?></option>
                            <?php
                            }
                            ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">

                </div>
            </form>
        </div>
        <div class="col-xl-4 col-xxl-4 col-lg-4 col-md-4 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>Category</th>
                                        <th>Iteam Title</th>
                                        <th>Poster</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['itemid']); ?>" class="post_ids">
                                            </td>
                                            <td>
                                                <?php
                                                $cat_ids = explode(',', $row['cat_id']);
                                                foreach ($cat_ids as $cat_id) {
                                                    if (isset($categories[$cat_id])) {
                                                        _e($categories[$cat_id] . ",");
                                                    }
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <?php
                                                if (strlen($row['iteam_name']) > 25) {
                                                    _e(substr($row['iteam_name'], 0, 25)) . '...';
                                                } else {
                                                    _e($row['iteam_name']);
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <img type="image" src="images/<?php _e($row['image']); ?>" class="image_size" />
                                            </td>
                                            <td>
                                                <?php if ($row['status'] != "0") { ?>
                                                    <a title="Change Status" class="toggle_btn_a" href="javascript:void(0)" data-id="<?php _e($row['itemid']); ?>" 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['itemid']); ?>" 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_album.php?item_id=<?php _e($row['itemid']); ?>" class="btn btn-primary">
                                                    <i class="bi bi-pencil-square"></i>
                                                </a>
                                                <a href="javascript:void(0)" data-id="<?php _e($row['itemid']); ?>" 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, .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_iteams';

            $.ajax({
                type: 'post',
                url: 'processdata.php',
                dataType: 'json',
                data: {
                    id: _id,
                    for_action: _for,
                    column: _column,
                    table: _table,
                    'action': 'toggle_status',
                    'tbl_id': 'itemid'
                },
                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_iteams';

            swal({
                    title: "Are you sure you want to delete this Iteam?",
                    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: "Iteam is deleted...",
                                        type: "success"
                                    }, function() {
                                        location.reload();
                                    });
                                } else if (res.status == '-2') {
                                    swal(res.message);
                                }
                            }
                        });
                    } 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_iteams';

                            $.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 Iteam 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"); ?>