<?php
include_once("../include/main.inc.php");
check_session('MyCpanel', 'index.php');

################ Paging Starts From Here ##################
@extract($_REQUEST);
$start = (intval($start) == 0 or $start == "") ? $start = 0 : $start;
$pagesize = intval($pagesize) == 0 ? $pagesize = 100 : $pagesize;
if ($parentID == "") {
    $parentID = 0;
}
$heading = "Manage Categories";
$record_type = "Category";
$script_name = "manage-category.php";
$table_name = "category_tbl";
#################### Add Record ##################
if ($_REQUEST['action'] == "add_record" && $catName != "") {
    $count_category = mysqli_query($dbconn, "select * from $table_name ");

    $sql = mysqli_query($dbconn, "select * from $table_name where catName='$catName' and parentID='$parentID'");
    $num = mysqli_num_rows($sql);
    if ($num > 0) {
        $_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' already exist  </div>';
    } else {
        if ($_FILES['image']['nam'] != "") {
            $file_extension = strtolower(getExtension($_FILES['image']['name']));
            if ($_FILES['image']['name'] != "") {
                $img_name = $catName . date("s");
                $img = upload_file($img_name, "image", "uploaded-files/category/images");

                $width = "50";
                $height = "50";
                $source_folder = SITE_DIR_PATH . "/uploaded-files/category/images/";
                $destination_folder = SITE_DIR_PATH . "/uploaded-files/category/images/thumbs/";
                saveResizedImage($img, $width, $height, $source_folder, $destination_folder);
            }
        }
        if ($_FILES['banner']['name'] != "") {
            $file_extension = strtolower(getExtension($_FILES['banner']['name']));
            if ($_FILES['banner']['name'] != "") {
                $banner_name = $catName . "-banner" . date("s");
                $banner = upload_file($banner_name, "banner", "uploaded-files/category/banners");
            }
        }
        $maxRes = db_fetch_array(db_query("select max(catOrder) from $table_name where parentID='$parentID'"));
        $catOrder = $maxRes[0] + 1;
        $sql = db_query("insert into $table_name set parentID='$parentID', catName='$catName', catDesc='$catDesc', catImage='$img', catOrder='$catOrder', catBanner='$banner'");
        $_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been added successfully  </div>';

        header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
        exit;
    }
}

####################################################

if ($action == "Update") {
    $input = $_POST;
    $part = array_splice($input, 0, 2);

    while (list($key, $val) = each($input)) {
        if (substr($key, 0, 6) == "order_") {
            $key1 = substr($key, 6, strlen($key) - 6);

            $qry1 = db_query("update $table_name set catOrder='$val' where catID='$key1'");
        }
    }
    //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been updated successfully  </div>';

    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}

if ($id == "delete_record") {
    $categoryRes = getResult($table_name, " where catID='$catID'");
    $filename = $categoryRes['catImage'];
    $bannername = $categoryRes['catBanner'];
    if ($filename != "") {
        $file = SITE_DIR_PATH . "/uploaded-files/category/images/" . $filename;
        if (file_exists($file)) {
            unlink($file);
        }
        $file_thumb = SITE_DIR_PATH . "/uploaded-files/category/images/thumbs/" . $filename;
        if (file_exists($file_thumb)) {
            unlink($file_thumb);
        }
        $file_banner = SITE_DIR_PATH . "/uploaded-files/category/banners/" . $filename;
        if (file_exists($file_thumb)) {
            unlink($file_thumb);
        }
    }
    db_query("update $table_name SET status = 'D' where catID='$catID'");
    //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been deleted successfully  </div>';

    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}


if (isset($_POST['active'])) {
    if (!empty($_POST['cat_arr'])) {
        $catid = $_POST['cat_arr'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "UPDATE $table_name SET status = 'Y' WHERE catID = '$id'");
            mysqli_query($dbconn, "UPDATE wps_meta_tags SET status = 'Y'  WHERE entity_id='$id' AND entity_name='category' AND  page_table='$table_name'");
        }
        //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been updated successfully</div>';
    } else {
        //$_SESSION['session_message'] = '<div class="btn btn-danger">No Category selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['inactive'])) {
    if (!empty($_POST['cat_arr'])) {
        $catid = $_POST['cat_arr'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "UPDATE $table_name SET status = 'N'  WHERE catID = '$id'");
            mysqli_query($dbconn, "UPDATE wps_meta_tags SET status = 'N'  WHERE entity_id='$id' AND entity_name='category' AND  page_table='$table_name'");
        }
        //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been updated successfully</div>';
    } else {
        //$_SESSION['session_message'] = '<div class="btn btn-danger">No Category selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['delete'])) {
    if (!empty($_POST['cat_arr'])) {
        $catid = $_POST['cat_arr'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "delete from wps_meta_tags WHERE entity_id='$id' AND entity_name='category' AND  page_table='$table_name'");
            mysqli_query($dbconn, "UPDATE $table_name SET status = 'D' WHERE catID = '$id'");
          
        }
        //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been deleted successfully</div>';
    } else {
        //$_SESSION['session_message'] = '<div class="btn btn-danger">No Category selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['set_home'])) {
    if (!empty($_POST['cat_arr'])) {
        $catid = $_POST['cat_arr'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "UPDATE $table_name SET home_category = 1 WHERE catID = '$id'");
        }
        //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been updated successfully</div>';
    } else {
        //$_SESSION['session_message'] = '<div class="btn btn-danger">No Category selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['unset_home'])) {
    if (!empty($_POST['cat_arr'])) {
        $catid = $_POST['cat_arr'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "UPDATE $table_name SET home_category = 0 WHERE catID = '$id'");
        }
        //$_SESSION['session_message'] = '<div class="btn btn-success">' . $record_type . ' has been updated successfully</div>';
    } else {
        //$_SESSION['session_message'] = '<div class="btn btn-danger">No Category selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&parentID=" . $parentID . "&catID=" . $catID . "&pagesize=" . $pagesize);
    exit;
}
########################################################
admin_header("Manage $record_type");
$qry = mysqli_query($dbconn, "SELECT * FROM $table_name WHERE parentID = '$parentID' AND status IN ('Y', 'N')");
?>
<div class="content-wrapper">
    <div class="page-header">
        <h3 class="page-title">
            <?= $heading; ?>
        </h3>

        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="nav-item d-none d-lg-flex">
                    <?php
                    if ($parentID != "" && $parentID != 0) {
                        page_nav($parentID);
                    }
                    ?>
                </li>

                <li class="nav-item d-none d-lg-flex">
                    <a class="nav-link" href="<?= admin_url ?>addeditcategory.php?parentID=<?= $parentID; ?>">
                        <span class="btn btn-primary">+ Add New Category</span>
                    </a>
                </li>
            </ol>
        </nav>
    </div>
    <div class="card">
        <div class="card-body">
            <div class="row">
                <div class="col-12">
                    <form action="" method="post">
                        <div class="table-responsive">
                            <table id="order-listing" class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th class="_reab">#</th>
                                        <th>S.No.</th>
                                        <th>Heading</th>
                                        <th>Header Menu</th>
                                        <th>Image</th>
                                        <th>View Order</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sl = $start + 1;
                                    while ($arr = mysqli_fetch_array($qry)) {
                                        $catID = $arr['catID'];
                                        $sub_cat_query = mysqli_query($dbconn, "SELECT * from $table_name where parentID = '$catID'");
                                        $faq_query = mysqli_query($dbconn, "SELECT * from faq_tbl where category_id = '$catID'"); ?>
                                        <tr>
                                            <td>
                                                <div class="form-check mt-0">
                                                    <label class="form-check-label">
                                                        <input type="checkbox" class="form-check-input" name="cat_arr[]" value="<?= $arr['catID'] ?>">
                                                        <i class="input-helper"></i>
                                                    </label>
                                                </div>
                                            </td>
                                            <td><?= $sl ?></td>
                                            <td>
                                                <p class="ordern"><?= $arr['catName']; ?></p>
                                                <?php //echo ($arr['home_category'] == '1') ? 'Set As Home Category' : "";
                                                ?>
                                                <p class="user-dcs">
                                                    <a href="<?= SITE_ADMIN_URL; ?>/<?= $script_name; ?>?parentID=<?= $arr['catID']; ?>">Sub
                                                        Categories <span>[<?= mysqli_num_rows($sub_cat_query) ?>]</span></a>
                                                </p>
                                                <p class="user-dcs">
                                            <a href="<?= SITE_ADMIN_URL; ?>/manage-faqs.php?category_id=<?= $arr['catID']; ?>"> FAQ <span>[<?= mysqli_num_rows($faq_query) ?>]</span></a>
                                        </p>
                                                <p class="user-dcs">
                                                    <a href="<?= SITE_ADMIN_URL; ?>/manage_location_content.php?category_id=<?= $arr['catID']; ?>">Sub
                                                        Domain Content </a>
                                                </p>
                                            </td>
                                            <td>
                                                <label class="toggleSwitch">
                                                    <input type="checkbox" id="toggle-input" data-catid="<?= $arr['catID']; ?>" <?=$arr['header_menu'] == 'Y'? 'checked':'';?>>
                                                    <span>

                                                             <span>No</span>
                                                             <span>Yes</span>
                                                    </span>
                                                    <a></a>
                                                </label>
                                            </td>
                                            <td>
                                                <?php
                                                if ($arr['catImage'] != "") {
                                                    $file1 = SITE_DIR_PATH . "/uploaded-files/category/images/" . $arr['catImage'];
                                                    $dimens = GetImageSize($file1);
                                                    if ($dimens[0] > 130) {
                                                        $dimens[0] = $dimens[0] + 30;
                                                        $dimens[1] = $dimens[1] + 80;
                                                    } else {
                                                        $dimens[0] = 200;
                                                        $dimens[1] = 200;
                                                    }
                                                ?>
                                                    <a href="javascript:void(0);" onClick="openwin('<?= SITE_ADMIN_URL; ?>/popup_new.php?img=category/images/<?= $arr['catImage']; ?>', '<?= $dimens[0]; ?>', '<?= $dimens[1]; ?>')" class="pay-status-dcs">

                                                    <span class="adminThumb">
                                                        <!-- <img src="<? //= SITE_ADMIN_URL; ?>/popup_new.php?img=category/images/<? //= $arr['catImage']; ?>', '<? //= $dimens[0]; ?>', '<? //= $dimens[1]; ?>'"> -->
                                                        <img src="<?=site_url?>/uploaded-files/category/images/<?= $arr['catImage']; ?>">
                                                    </span>

                                                    </a>
                                                <?php } ?>
                                            </td>
                                            <td>
                                                <input name="order_<?= $arr['catID']; ?>" class="form-control order" type="text" size="2" value="<?= $arr['catOrder']; ?>">
                                            </td>
                                            <!-- <td>
                                        <a href="<?= SITE_ADMIN_URL; ?>/manage_price.php?category_id=<?= $arr['catID']; ?>" class="rec-date-dcs">Manage Price/Variants (<?= $arr['v']; ?>)</a>
                                    </td> -->
                                            <td>
                                                <p class="status-dcs"><?php if ($arr['status'] == 'Y') { ?><label class="badge badge-success badge-pill">Active</label><?php } else if ($arr['status'] == 'N') { ?> <label class="badge badge-danger badge-pill">In-Active</label>
                                                    <?php 
                                             } else if ($arr['status'] == 'D') { ?>
                                                 <label class="badge badge-secondary badge-pill">Deleted</label>
                                             <?php 
                                             } else { ?>
                                                 <label class="badge badge-warning badge-pill">Deleted</label> <!-- fallback -->
                                             <?php } ?></p>
                                            </td>
                                            <td>
                                                <p class="download-dcs"><a href="<?= SITE_ADMIN_URL ?>/addeditcategory.php?start=<?= $start; ?>&catID=<?= $arr['catID']; ?>&parentID=<?= $parentID; ?>&pagesize=<?= $pagesize; ?>">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-3">
                                                            <path d="M12 20h9"></path>
                                                            <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
                                                        </svg>
                                                    </a></p>
                                            </td>
                                        </tr>

                                    <?php $sl++;
                                    } ?>

                                </tbody>
                            </table>
                            <div class="btn-grp">
                                <button type="submit" name="active" onclick="return select_chk()" class="btn btn-success btn-icon-text btn-sm">
                                    <i class="fas fa-toggle-on mr-1"></i>Activate
                                </button>
                                <button type="submit" name="inactive" onclick="return select_chk()" class="btn btn-warning btn-icon-text btn-sm">
                                    <i class="far fa-times-circle mr-1"></i>Deactivate
                                </button>
                                <button type="submit" name="set_home" onclick="return select_chk()" class="btn btn-primary btn-icon-text btn-sm">
                                    <i class="far fa-check-square mr-1"></i>Set
                                </button>
                                <button type="submit" name="unset_home" onclick="return select_chk()" class="btn btn-info btn-icon-text btn-sm">
                                    <i class="fa fa-exclamation-triangle mr-1"></i>Unset
                                </button>

                                <button type="submit" name="action" value="Update" class="btn btn-default btn-icon-text btn-sm">
                                    <i class="far fa-check-square mr-1"></i>Update Order
                                </button>
                                <button type="submit" name="delete" onclick="return select_chk()" class="btn btn-danger btn-icon-text btn-sm">
                                    <i class="fas fa-trash-alt mr-1"></i>Delete
                                </button>

                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script language="javascript">
    function select_chk() {
        var chks = document.getElementsByName('cat_arr[]');
        var hasChecked = false;
        for (var i = 0; i < chks.length; i++) {
            if (chks[i].checked) {
                hasChecked = true;
                break;
            }
        }
        if (hasChecked == false) {
            alert("Please Select At Least One.");
            return false;
        }
    }
</script>



<?php
admin_footer();
?>
<script>
$(document).ready(function() {
    $(document).on('change', '#toggle-input', function(){

                var isChecked = $(this).is(':checked');
                var categoryId = $(this).data('catid');
                var finalStatus = (isChecked == false) ? 'N' : 'Y';
                // alert(finalStatus);
                $.ajax({
                    url: '<?= SITE_ADMIN_URL; ?>/category_switch.php',
                    type: 'POST',
                    data: {
                        checked: finalStatus,
                        category_id: categoryId
                    },
                    success: function(response) {
                        console.log(response);
                    }
                });
            });
});
</script>