<?php
include_once("../include/main.inc.php");
check_session('MyCpanel','index.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

################ Paging Starts From Here ##################
@extract($_REQUEST);
$page = (isset($_REQUEST['page']) && $_REQUEST['page'] > 0)?$_REQUEST['page']:1;
$pagesize = isset($_GET['pagesize'])?$_GET['pagesize']:50;
$start = ($page-1)*$pagesize;


$heading="Manage ".(isset($_REQUEST['odrtype'])?$_REQUEST['odrtype']:'All')." Orders";
$record_type="Orders";
$script_name="manage-orders.php";
$table_name="orders_tbl1";

$agent_ary = mysqli_query($dbconn, "SELECT slno, name FROM admin_details WHERE status = 'Y'");
$agents = [];
while($agnt = mysqli_fetch_array($agent_ary)){
    $agents[$agnt['slno']] = $agnt['name'];
}

if (isset($_POST['e-kyc'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET ekyc = 'COMPLETED' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">e-KYC has sdsbeen updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['video'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET video = 'COMPLETED' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Video has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start ."&pagesize=" . $pagesize);
    exit;
}


if (isset($_POST['download'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET download = 'COMPLETED' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['status_active'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET order_status = 'ACTIVE' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?msg=active&start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['status_inactive'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET order_status = 'INACTIVE' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?msg=inactive&start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['payment_paid'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET payment_status = 'SUCCESS' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?msg=active&start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['delivered'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET delivery_status = 'DELIVERED' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_POST['dongle_dispatch'])) {
    if (!empty($_POST['arr_ids'])) {
        $orderIDs = $_POST['arr_ids'];
        foreach ($orderIDs as $orderID) {
            mysqli_query($dbconn, "UPDATE $table_name SET delivery_status = 'DISPACHED' WHERE order_id = '$orderID'");
        }
        $_SESSION['session_message'] = '<div class="btn btn-success">Order has been updated successfully</div>';
    } else {
        $_SESSION['session_message'] = '<div class="btn btn-danger">No orders selected</div>';
    }
    header("Location: " . SITE_ADMIN_URL . "/" . $script_name . "?start=" . $start . "&pagesize=" . $pagesize);
    exit;
}

if (isset($_REQUEST["delete_record"])) {
    if (!empty($_POST['arr_ids'])) {
        $catid = $_POST['arr_ids'];
        foreach ($catid as $id) {
            mysqli_query($dbconn, "delete from $table_name WHERE order_id = '$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 . "?msg=delete&start=" . $start . "&pagesize=" . $pagesize);
    exit;

}

########################################################
admin_header();

?>
<style>
    .showmore{display: none;}
    h6.text-center.showless {
        font-size: 10px;
        cursor: pointer;
    }
    .filter{
        float: right;
        margin-bottom: 5px;
        text-align: right;
    }
    .filter .filter-group{
        display: inline-block;
        width: 11%;
        font-size: 10px;
        text-align: left;
    }
    .filter .filter-group label{
        margin-bottom: 2px;
    }
    .filter input, .filter select, .filter button, .filter a{
        border: 1px solid #ccc;
        margin-bottom: 5px;
        width: 100%;
        font-size: 12px;
    }
    .filter button{
        background-color: #26ade4;
        color: #fff;
        cursor: pointer;
        border: 1px solid #26ade4;
        font-weight: 700;
    }
    .filter a{
        background-color: #673AB5;
        color: #fff;
        cursor: pointer;
        border: 1px solid #673AB7;
        font-weight: 700;
        padding: 2px 10px;
    }
</style>

<div class="content-wrapper">
    <div class="page-header">
        <h3 class="page-title">
            <?= $heading;?>
        </h3>
        <nav aria-label="breadcrumb">
		    <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="welcome.php">Admin</a></li>
                <li class="breadcrumb-item active" aria-current="page">Manage Orders</li>
            </ol>
        </nav>
    </div>
    <div class="card">
        <div class="card-body p-1">
            <?php if(isset($_REQUEST['msg'])){?>
            <div class="alert alert-success text-center">
                <h5>
                    <?= ($_REQUEST['msg'] == 'delete')?'Order deleted successfully':''; ?>
                    <?= ($_REQUEST['msg'] == 'inactive')?'Order Marked as inactive successfully':''; ?>
                    <?= ($_REQUEST['msg'] == 'active')?'Order Marked as avtive successfully':''; ?>
                </h5>
            </div>
            <?php } ?>
        
        <div class="row">
            
            <div class="col-md-12">
                <form action="" class="filter">
                    <div class="filter-group">
                        <label>Keyword</label>
                        <input type="text" placeholder="Enter Keyword" name="f_keyword" value="<?= isset($_REQUEST['f_keyword'])?$_REQUEST['f_keyword']:''?>">
                    </div>
                    <div class="filter-group">
                        <label>From date</label>
                        <input type="date" placeholder="From date" name="f_sdate" value="<?= isset($_REQUEST['f_sdate'])?$_REQUEST['f_sdate']:''?>">
                    </div>
                    <div class="filter-group">
                        <label>To date</label>   
                        <input type="date" placeholder="To date" name="f_tdate" value="<?= isset($_REQUEST['f_tdate'])?$_REQUEST['f_tdate']:''?>">
                    </div>
                    <div class="filter-group">
                        <label>Payment status</label>
                        <select name="f_payment">
                            <option value="">Payment Status</option>
                            <option value="PENDING" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='PENDING')?'selected':''?>>Pending</option>
                            <option value="SUCCESS" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='SUCCESS')?'selected':''?>>Paid</option>
                            <option value="PARTIAL" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='PARTIAL')?'selected':''?>>Partial</option>
                            <!-- <option value="ABORTED" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='ABORTED')?'selected':''?>>Aborted</option>
                            <option value="FAILUR" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='FAILUR')?'selected':''?>>Failur</option>
                            <option value="INVALID" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='INVALID')?'selected':''?>>Invalid</option>
                            <option value="TIMEOUT" <?= (isset($_REQUEST['f_payment']) && $_REQUEST['f_payment']=='TIMEOUT')?'selected':''?>>Timeout</option> -->
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Oerder Type</label>
                        <select name="f_order">
                            <option value="">Order Status</option>
                            <option value="COMPLETED" <?= (isset($_REQUEST['f_order']) && $_REQUEST['f_order']=='COMPLETED')?'selected':''?>>Completed</option>
                            <option value="PENDING" <?= (isset($_REQUEST['f_order']) && $_REQUEST['f_order']=='PENDING')?'selected':''?>>Pending</option>
                        </select>
                    </div>
                    <?php if($_SESSION['MyAdminUserType'] == 'admin'){?>
                    <div class="filter-group">
                        <label>Agent</label>
                        <select name="f_agent">
                            <option value="">Assigned Agent</option>
                            <?php
                                
                                foreach($agents as $aid => $aname){
                                    echo '<option value="'.$aid.'" '.((isset($_REQUEST['f_agent']) && $_REQUEST['f_agent']==$aid)?'selected':'').'>'.$aname.'</option>';
                                }
                            ?>
                            <option value="unassigned" <?= (isset($_REQUEST['f_agent']) && $_REQUEST['f_agent']=='unassigned')?'selected':''?>>Un-Assigned</option>
                        </select>
                    </div>
                    <?php } ?>
                    <div class="filter-group"><button type="submit">GET DATA</button></div>
                    <?php if($_SESSION['MyAdminUserType'] == 'admin'){?>
                    <div class="filter-group"><a href="manage-order-download.php?<?= http_build_query($_GET); ?>">EXPORT EXCEL</a></div>
                    <?php } ?>
                </form>
            </div>
        </div>
        <form action="" method="post">
            <div class="table-responsive">
                <table class="table table-bordered table-hover table-striped">
                    <thead>
                        <tr>
                            <th class="_reab" style="width:2%;">
                                #
                                <div class="form-check mt-0">
                                    <label class="form-check-label">
                                    <input type="checkbox" class="form-check-input" name="check_all" id="check_all" value="1" onclick="checkall(this.form)">
                                    <i class="input-helper"></i>
                                    </label>
                                </div>
                            </th>
                            <th>Sn.</th>
                            <th style="width:30%;">Order No./User Info.</th>
                            <th style="width:30%;">Order Details</th>
                            <th style="width:8%;">Payment Status</th>
                            <th style="width:5%;">Order Status</th>
                            <th style="width:5%;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $sl=$start+1;
                            if($_SESSION['MyAdminUserType'] == 'admin'){
                                $whr = ' WHERE order_id>0';
                            }else{
                                $whr = ' WHERE agentId='.$_SESSION['MyAdminUserSLNO'];
                            }
                            if(isset($_REQUEST['f_order']) && !empty($_REQUEST['f_order'])){
                                if($_REQUEST['f_order'] == 'COMPLETED'){
                                    $whr .= " AND (CASE WHEN  ekyc='NA' THEN ekyc='NA' ELSE (ekyc='COMPLETED' AND video='COMPLETED' AND caApproval='COMPLETED' AND download_status='COMPLETED') END) AND (CASE WHEN delivery_status='NA' THEN delivery_status='NA' ELSE (delivery_status='COMPLETED' OR delivery_status='DISPATCHED') END) ";  
                                }

                                if($_REQUEST['f_order'] == 'PENDING'){
                                    $whr .= " AND (CASE WHEN  ekyc='NA' THEN ekyc='NA' ELSE (ekyc!='COMPLETED' OR video!='COMPLETED' OR caApproval!='COMPLETED' OR download_status!='COMPLETED') END) AND (CASE WHEN delivery_status='NA' THEN delivery_status='NA' ELSE (delivery_status!='COMPLETED' AND delivery_status!='DELIVERED' AND delivery_status!='DISPATCHED') END) ";  
                                }
                            }
                            if(isset($_REQUEST['f_sdate']) && !empty($_REQUEST['f_sdate'])){$whr .= " AND order_date>='".date('Y-m-d 0:0:0', strtotime($_REQUEST['f_sdate']))."'"; }
                            if(isset($_REQUEST['f_tdate']) && !empty($_REQUEST['f_tdate'])){$whr .= " AND order_date<='".date('Y-m-d 23:59:59', strtotime($_REQUEST['f_tdate']))."'"; }
                            if(isset($_REQUEST['f_payment']) && !empty($_REQUEST['f_payment'])){$whr .= " AND payment_status='".$_REQUEST['f_payment']."'"; }
                            if(isset($_REQUEST['f_agent']) && !empty($_REQUEST['f_agent'])){
                                if($_REQUEST['f_agent'] == 'unassigned'){
                                    $whr .= " AND agentId IS NULL"; 
                                }else{
                                    $whr .= " AND agentId=".$_REQUEST['f_agent']; 
                                }
                            }
                            if(isset($_REQUEST['f_delivery']) && !empty($_REQUEST['f_delivery'])){
                                if($_REQUEST['f_delivery'] == 'PENDING'){
                                    $whr .= " AND delivery_status='PENDING' AND (ekyc='COMPLETED' OR ekyc='NA') AND (video='COMPLETED' OR video='NA') AND (download_status='COMPLETED' OR download_status='NA') AND (caApproval='COMPLETED' OR caApproval='NA') ";
                                }else{
                                    $whr .= " AND delivery_status='".$_REQUEST['f_delivery']."'";
                                }
                             }

                            if(isset($_REQUEST['f_keyword']) && !empty($_REQUEST['f_keyword'])){$whr .= " AND (applicants_name LIKE '%".$_REQUEST['f_keyword']."%' OR applicants_org LIKE '%".$_REQUEST['f_keyword']."%' OR applicants_mobile LIKE '%".$_REQUEST['f_keyword']."%' OR bill_ogname LIKE '%".$_REQUEST['f_keyword']."%' OR bill_address LIKE '%".$_REQUEST['f_keyword']."%')"; }

                            $qry= mysqli_query($dbconn,"SELECT orders_tbl1.*, customer_tbl.cname, cemail, cmobile, SUM(requested_amount) AS paid_amount FROM orders_tbl1 LEFT JOIN customer_tbl ON customer_tbl.cid=orders_tbl1.customer_id LEFT JOIN order_payment_history ON order_payment_history.invoice_id=orders_tbl1.invoice_id ".$whr." GROUP BY orders_tbl1.invoice_id ORDER BY order_id DESC LIMIT ".$start.", ".$pagesize);

                            if(!$qry){
                                echo mysqli_error($dbconn);
                            }

                            $itms = mysqli_query($dbconn,"SELECT oi.*, catName FROM order_items AS oi LEFT JOIN category_tbl AS ct ON oi.category_id=ct.catID ");
                            $odritm = [];

                            

                            while($itm = mysqli_fetch_array($itms)){
                                $odritm[$itm['invoice_id']][] = $itm;
                            }

                            while($arr=mysqli_fetch_array($qry)) {
                        ?>
                        <tr>
                            <td>
                                <div class="form-check mt-0">
                                    <label class="form-check-label">
                                        <input type="checkbox" class="form-check-input allSelect" name="arr_ids[]" value="<?= $arr['order_id'] ?>"><i class="input-helper"></i>
                                    </label>
                                </div>
                            </td>
                            <td>
                                <?= $sl?>
                            </td>
                            <td>
                                <?= !empty($arr['success_order_id'])?'<p class="ordern"> '.$arr['success_order_id'].'</p>':'';?>
                                <p class="user-dcs"><span>User: </span>  <?= strtoupper($arr['cname']).' | Mobile: '.$arr['cmobile'].' | Email: '.$arr['cemail'] ?></p>
                                <p class="user-dcs"><span>Applicants: </span>  <?= strtoupper($arr['applicants_name']); ?> | Mobile: <?= $arr['applicants_mobile']; ?> | Email: <?= $arr['applicants_email'];?></p>
                                <?php if(!empty($arr['applicants_org'])){?>
                                    <p class="email-dcs"><span>Organization: </span> <?= $arr['applicants_org'];?> <?= !empty($arr['applicants_org'])?'('.$arr['bill_gst'].')':'';?></p>
                                <?php } ?>
                                
                                <div>
                                    <h6 class="text-center showless">Show More</h6>
                                    <div class="showmore">
                                        <p class="address-dcs"><span>Billing Address: </span> <?=$arr['bill_address'];?>,<?=$arr['bill_city'];?>,<?=$arr['bill_state'];?>,Pincode-<?=$arr['bill_zip'];?>,<?=$arr['bill_country'];?></p>	
                                        <p class="address-dcs "><span>Delivery Address: </span> <?=$arr['delivery_address'];?>,<?=$arr['delivery_city'];?>,<?=$arr['delivery_state'];?>,Pincode-<?=$arr['delivery_zip'];?>,<?=$arr['delivery_country'];?></p>	
                                    </div>

                                </div>
                                <p class="rec-date-dcs"><?= date('d M Y, h:ia', strtotime($arr['order_date']));?></p>
                                <p class="user-dcs mt-2">Agent: <?= isset($agents[$arr['agentId']])?'<b>'.$agents[$arr['agentId']].'</b>':'<span class="text-danger">Not assigned</span>'; ?></p>
                            </td>
                            <td>
                                <ol>
                                <?php $ons =1; foreach($odritm[$arr['invoice_id']] as $ot){ ?>
                                    <li class="user-dcs"> <span><?= empty($ot['brand'])?'Token':'Signature';?>:</span> <?= $ot['catName'];?> 
                                    <?php if(!empty($ot['brand'])){echo '</br><span>'.$ot['brand'].'</span>';} ?> 
                                    
                                    <?php if(!empty($ot['validity'])){echo '<span>, '.$ot['validity'].'</span>';} ?>
                                    <?php if(!empty($ot['user_type'])){echo '<span>, '.$ot['user_type'].'</span>';} ?>
                                    <?php if(!empty($ot['validation'])){echo '<span>, '.$ot['validation'].' Year</span>';} ?>
                                    <?php if(!empty($ot['token_type'])){echo '<span>, '.$ot['token_type'].'</span>';} ?>
                                    
                                    <?php if(empty($ot['brand'])){echo '<span>, Qty-'.$ot['quantity'].'</span>';} ?>
                                </li>
                                    <!-- <p class="user-dcs border-bottom pb-2">
                                        Price: <span>₹<?= round($ot['price_each']).' X '.$ot['quantity'] ?> = ₹<?=$ot['quantity']*$ot['price_each'];?></span>
                                    </p> -->
                                <?php } ?>
                                </ol>
                                <div class="mt-1">
                                    <b>Total Order Value</b>
                                    <p class="total-am-dcs">₹ <?= $ttl = ($arr['total_amount']-$arr['discount'])+$arr['gst_amount'] ?></p>
                                </div>
                                <div class="mt-1">
                                    Order Type: <?= ($arr['order_status'] == 'ACTIVE')?'<label class="text-success ml-2">Active</label>':'<label class="text-danger ml-2">INACTIVE</label>'; ?>
                                </div>
                            </td>
                            <td>
                                
                                <?php if($arr['paid_amount'] == 0){echo '<label class="badge badge-danger badge-pill">PENDING</label>';}?>
                                <?php if($arr['paid_amount'] < $ttl && $arr['paid_amount'] > 0){echo '<label class="badge badge-info badge-pill">PARTIAL</label>';}?>
                                <?php if($arr['paid_amount'] >= $ttl){echo '<label class="badge badge-success badge-pill">Paid</label>';}?>
                                
                                <?php if($arr['paid_amount'] < $ttl){?>
                                <p>Balance Amount: ₹<?= $ttl-$arr['paid_amount']; ?></p>
                                <?php } ?>
                            </td>

                            <td>
                                

                                <?php 
                                    $o_status = $o_complete =  0;
                                    if($arr['ekyc'] != 'NA'){$o_status += 1; if($arr['ekyc'] == 'COMPLETED'){$o_complete +=1;}}
                                    if($arr['video'] != 'NA'){$o_status += 1; if($arr['video'] == 'COMPLETED'){$o_complete +=1;}}
                                    if($arr['caApproval'] != 'NA'){$o_status += 1; if($arr['caApproval'] == 'COMPLETED'){$o_complete +=1;}}
                                    if($arr['download_status'] != 'NA'){$o_status += 1; if($arr['download_status'] == 'COMPLETED'){$o_complete +=1;}}
                                    if($arr['delivery_status'] != 'NA'){$o_status += 1; if($arr['delivery_status'] == 'DELIVERED' || $arr['delivery_status'] == 'DISPATCHED'){$o_complete +=1;}}
                                ?>

                                <div class="mb-1 text-center">
                                    <?= ($o_status == $o_complete)?'<label class="badge badge-success badge-pill">COMPLETED</label>':'<label class="badge badge-danger badge-pill">PENDING</label>'; ?>
                                </div>

                                <h6 class="text-center showless">Show More</h6>
                                <div class="showmore">
                                    <?php if($arr['ekyc'] != 'NA'){?>
                                    <div class="kyc-status-admin">
                                        <label for="e-Kyc">e-Kyc</label>
                                        <?= ($arr['ekyc'] == 'COMPLETED')?'<span class="text-success">COMPLETED</span>':'<span class="text-danger">'.$arr['ekyc'].'</span>'; ?>
                                    </div>
                                    <?php } ?>

                                    <?php if($arr['video'] != 'NA'){?>
                                    <div class="kyc-status-admin">
                                        <label for="Video">Video Verif.</label>
                                        <?= ($arr['video'] == 'COMPLETED')?'<span class="text-success">COMPLETED</span>':'<span class="text-danger">'.$arr['video'].'</span>'; ?>
                                    </div>
                                    <?php } ?>

                                    <?php if($arr['caApproval'] != 'NA'){?>
                                    <div class="kyc-status-admin">
                                        <label for="Download" title="CA APPROVAL">CA-Appr.</label>
                                        <?= ($arr['caApproval'] == 'COMPLETED')?'<span class="text-success">COMPLETED</span>':'<span class="text-danger">'.$arr['caApproval'].'</span>'; ?>
                                    </div>
                                    <?php } ?>
                                   
                                    
                                    <?php if($arr['download_status'] != 'NA'){?>
                                    <div class="kyc-status-admin">
                                        <label for="Download">Download</label>
                                        <?= ($arr['download_status'] == 'COMPLETED')?'<span class="text-success">COMPLETED</span>':'<span class="text-danger">'.$arr['download_status'].'</span>'; ?>
                                    </div>
                                    <?php } ?>
                                    <?php if($arr['delivery_status'] != 'NA'){?>
                                    <div class="kyc-status-admin">
                                        <label for="Download">Delivery </label>
                                        <?= ($arr['delivery_status'] == 'DELIVERED')?'<span class="text-success">COMPLETED</span>':'<span class="text-danger">'.$arr['delivery_status'].'</span>'; ?>
                                        
                                    </div>
                                    <?php } ?>	
                                </div>

                                
                            </td>

                            <td>
                                <a class="badge badge-info text-white" href="manage-order-detail.php?orderid=<?= $arr['order_id']; ?>">VIEW DETAILS</a>
                            </td>
                        </tr>

                        <?php  $sl++; }?>

                    </tbody>
                </table>
                <div class="container">
                    <div class="row">
                        <div class="col-md-5">
                            <div class="dataTables_info" id="order-listing_info" role="status" aria-live="polite">Showing <?= $start+1; ?> to <?= $start+mysqli_num_rows($qry); ?> of <?= $row = mysqli_num_rows(mysqli_query($dbconn, "SELECT order_id FROM orders_tbl1 ".$whr))?> entries</div>
                        </div>
                        <div class="col-md-7">
                            <div class="dataTables_paginate paging_simple_numbers float-right">
                                <ul class="pagination">
                                    <li class="paginate_button page-item previous disabled" id="order-listing_previous">
                                        <a href="#" aria-controls="order-listing" data-dt-idx="0" tabindex="0" class="page-link">Previous</a>
                                    </li>
                                    <?php 
                                        $tpage = ceil($row/$pagesize);
                                        $prm = $_GET;
                                        unset($prm['page']);
                                        for($i=1; $i <= $tpage; $i++){
                                    ?>
                                    <li class="paginate_button page-item <?= ($i == $page)?'active':''?>">
                                        <a href="<?= $_SERVER['PHP_SELF']; ?>?page=<?= $i;?>&<?= http_build_query($prm)?>" aria-controls="order-listing" data-dt-idx="1" tabindex="0" class="page-link"><?= $i; ?></a>
                                    </li>
                                    <?php } ?>
                                    <li class="paginate_button page-item next disabled" id="order-listing_next">
                                        <a href="#" aria-controls="order-listing" data-dt-idx="2" tabindex="0" class="page-link">Next</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
            </div>
            <div class="btn-grp mt-2">
                <!-- <button type="submit" name="e-kyc" onclick="return select_chk()" class="btn btn-success btn-icon-text btn-sm">
                E-kyc Done
                </button>
                <button type="submit" name="video" onclick="return select_chk()" class="btn btn-warning btn-icon-text btn-sm">
                Video Done
                </button>
                <button type="submit" name="download" onclick="return select_chk()" class="btn btn-primary btn-icon-text btn-sm">
                Download Done
                </button>
                <button type="submit" name="send_email" onclick="return select_chk()" class="btn btn-info btn-icon-text btn-sm">
                Send Email
                </button>
                <button type="submit" name="status_active" onclick="return select_chk()" class="btn btn-success btn-icon-text btn-sm">
                Active
                </button>
                <button type="submit" name="status_inactive" onclick="return select_chk()" class="btn btn-success btn-icon-text btn-sm">
                Inactive
                </button>
                <button type="submit" name="payment_paid"  onclick="return select_chk()" class="btn btn-warning btn-icon-text btn-sm">
                Payment Paid
                </button>
                <button type="submit" name="delivered" onclick="return select_chk()" class="btn btn-primary btn-icon-text btn-sm">
                Delivered
                </button>
                <button type="submit"  name="dongle_dispatch" onclick="return select_chk()" class="btn btn-info btn-icon-text btn-sm">
                Dongle Dispatched
                </button> -->
                
                <button type="submit" name="status_active" onclick="return select_chk()" class="btn btn-success btn-icon-text btn-sm">Active</button>
                <button type="submit" name="status_inactive" onclick="return select_chk()" class="btn btn-danger btn-icon-text btn-sm">
                Inactive
                </button>
                <button type="submit" name="send_email" onclick="return select_chk()" class="btn btn-info btn-icon-text btn-sm">Send Email</button>
                <button type="submit" name="delete_record" onclick="return select_chk()" class="btn btn-danger btn-icon-text btn-sm">
                    Delete
                </button>
                </div>
        </form>
        </div>
    </div>
</div>
<style>
    .assignAgent {
        position: fixed;
        bottom: 7px;
        z-index: 99999;
        background: #fff;
        padding: 6px 5px;
        border: 1px solid #ccc;
        left: 13px;
        width: 250px;
        box-shadow: 0px 0px 4px 3px #060606;
        display: none;
    }

</style>
<div class="assignAgent">
    <div class="row">
        <div class="col-8">
            <select class="form-control form-control-sm p-0 pl-1" id="usrList">
                <option value="">Select agent</option>
                <?php
                    foreach($agents as $aid => $aname){
                    echo '<option value="'.$aid.'">'.$aname.'</option>';
                    }
                ?>
            </select>
        </div>
        <div class="col-4">
            <button type="button" class="btn btn-sm btn-success" id="ausr_btn">Assign</button>
        </div>
    </div>
</div>
<script language="javascript">

checked=false;
function checkall(frm1){
	var aa= frm1;
	if(checked == false){
		checked = true
	}
	else{
		checked = false
	}
	for (var i =0; i < aa.elements.length; i++){
		aa.elements[i].checked = checked;
	}
}

function select_chk(){
    var chks = document.getElementsByName('arr_ids[]');
    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;
    }else{
        
    }
}
</script>
<?php admin_footer(); ?>
<script>
    $(document).ready(function(){
        $('.showless').click(function(){
            let txt = $(this).text();
            $(this).text((txt == 'Show Less'?'Show More':'Show Less'));
            $(this).next().toggle();
        });

        $('.allSelect, #check_all').change(function(){
            let sn = 0;
            $('.allSelect').each(function(){
                if($(this).is(':checked')){
                    sn += 1;
                }
            });
            if(sn == 0){
                $('.assignAgent').hide();
            }else{
                $('.assignAgent').show();
            }
        });

        $('#ausr_btn').click(function(){
            let sn = [];
            $('.allSelect').each(function(){
                if($(this).is(':checked')){
                    sn.push($(this).val());
                }
            });
            if(sn.length){
                let user = $('#usrList').val();
                if(user.length){
                    $.ajax({
                        url: "<?= SITE_ADMIN_URL.'/form_ajax.php'?>",
                        data: {assign_agent_id: user, orderId: sn},
                        type: 'post',
                        dataType: 'JSON',
                        success: function(data){
                            if(data.success == true){
                                window.location.reload();
                            }else{
                                console.error();
                                alert(data.message);
                            }
                        }
                    });
                }else{
                    alert('Please select a agent to assign order');
                }
            }else{                
                alert('Please select atleast 1 order');                
            }
        });
    });
</script>
