<!-- Form -->
<div class="content-animation animated">
    <div class="row clearfix fBTitrBold ">
        <div class="row clearfix text-center">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                <div class="card ">
                    <div class="header">
                        <h2>
                            <button class="btn btn-success waves-effect waves-default refresh-request">
                                سیستم بازیافت
                            </button>
                        </h2>
                    </div>
                    <div class="body ">
                        <div class="row">
                            <div class="col-md-12" dir="ltr">
                                <div class="table-responsive text-center p-t-20 align-center no-overflow-y no-overflow-x">
                                    <table class="table table-bordered table-striped table-hover dataTable js-exportable-request text-center full_width"
                                           style="overflow-y: hidden">
                                        <thead>
                                        <tr>
                                            <td class="text-center">مامور مسئول</td>
                                            <td class="text-center">وضعیت</td>
                                            <td class="text-center">رضایت مندی</td>
                                            <td class="text-center">نوع</td>
                                            <td class="text-center">وزن</td>
                                            <td class="text-center">زمان تحویل برای</td>
                                            <td class="text-center">مکان انتخابی</td>
                                            <td class="text-center">مکان کاربر</td>
                                            <td class="text-center">شماره دوم</td>
                                            <td class="text-center">آدرس</td>
                                            <td class="text-center">کد ملی</td>
                                            <td class="text-center">شماره تماس</td>
                                            <td class="text-center">نام و نام خانوادگی</td>

                                            <td class="text-center">تاریخ ثبت</td>
                                            <td class="text-center">کد</td>
                                            <td class="text-center">شماره</td>
                                        </tr>
                                        </thead>
                                        <tbody class="bordered">

                                        </tbody>
                                        <tfoot>
                                        <tr>
                                            <td class="text-center">مامور مسئول</td>
                                            <td class="text-center">وضعیت</td>
                                            <td class="text-center">رضایت مندی</td>
                                            <td class="text-center">نوع</td>
                                            <td class="text-center">وزن</td>
                                            <td class="text-center">زمان تحویل برای</td>
                                            <td class="text-center">مکان انتخابی</td>
                                            <td class="text-center">مکان کاربر</td>
                                            <td class="text-center">شماره دوم</td>
                                            <td class="text-center">آدرس</td>
                                            <td class="text-center">کد ملی</td>
                                            <td class="text-center">شماره تماس</td>
                                            <td class="text-center">نام و نام خانوادگی</td>

                                            <td class="text-center">تاریخ ثبت</td>
                                            <td class="text-center">کد</td>
                                            <td class="text-center">شماره</td>
                                        </tr>
                                        </tfoot>
                                    </table>

                                    <script type="text/javascript">


                                        (function ($) {
                                            $(document).ready(function () {

                                                $('button.refresh-request').unbind().bind('tap, click', function (e) {
                                                    let btn = $(this);
                                                    btn.attr('disabled', 'disabled');
                                                    loadSystemData(btn);
                                                });

                                                let table = null;
                                                let loadSystemData = function (btn) {
                                                    LoadData({
                                                        request: 'proxy',
                                                        object: {},
                                                        action: 'recyclingController',
                                                        'header-type': 'pool'
                                                    }, null, false, function (data) {
                                                        if (table == null) {
                                                            table = $('.js-exportable-request');
                                                            table.find('tbody').empty().append(data);
                                                            table.DataTable({
                                                                responsive: true,
                                                                "language": {
                                                                    "lengthMenu": "Display _MENU_ records per page",
                                                                    "zeroRecords": " چیزی یافت نشد",
                                                                    "info": "نمایش از _START_ تا _END_ در _TOTAL_ رکورد",
                                                                    "infoEmpty": "<center>رکوردی پیدا نشد</center>",
                                                                    "infoFiltered": "(filtered from _MAX_ total records)",
                                                                    "paginate": {
                                                                        "next": "بعدی",
                                                                        "previous": "قبلی"
                                                                    }
                                                                },
                                                                "fnInfoCallback": function (oSettings, iStart, iEnd, iMax, iTotal, sPre) {
                                                                    event_request();
                                                                },
                                                                "fnDrawCallback": function (oSettings) {
                                                                    event_request();
                                                                }
                                                            });
                                                        } else {
                                                            table.find('tbody').empty().append(data);
                                                            table.dataTable();
                                                        }


                                                        event_request();
                                                        setTimeout(function () {
                                                            if (btn !== null) btn.removeAttr('disabled', 'disabled');
                                                        }, 30)
                                                    });
                                                };

                                                loadSystemData(null);
                                                let text = '', code = '', ID = '', btn = '';
                                                let event_request = function () {
                                                    $('button[data-action="request-action"]').unbind().bind('tap, click', function () {
                                                        let btn = $(this);

                                                        let action = btn.attr('data-mode');

                                                        switch (action) {
                                                            case 'show-location':
                                                                ShowLocation(btn);
                                                                break;
                                                            case 'add-agent':
                                                                AddAgent(btn);
                                                                break;
                                                            case 'add-status':
                                                                AddStatus(btn);
                                                                break;
                                                            default:
                                                                break;
                                                        }
                                                    });


                                                    $('button.model-option-status').unbind().bind('tap, click', function () {
                                                        let b = $(this);
                                                        code = b.attr('data-code');
                                                        text = b.text();
                                                        if (ID > 0) {
                                                            swal({
                                                                title: 'اخطار',
                                                                text: 'ویرایش شود؟',
                                                                type: "warning",
                                                                showCancelButton: true,
                                                                confirmButtonColor: "#DD6B55",
                                                                confirmButtonText: "بله ",
                                                                cancelButtonText: "نه ",
                                                                closeOnConfirm: false,
                                                                closeOnCancel: true
                                                            }, function (isConfirm) {
                                                                if (isConfirm) {
                                                                    LoadData({
                                                                        request: 'proxy',
                                                                        object: {
                                                                            request: ID,
                                                                            status: code
                                                                        },
                                                                        action: 'recyclingController',
                                                                        'header-type': 'status-request'
                                                                    }, null, false, function (data) {
                                                                        if (parseInt(data) === 1) {
                                                                            btn.text(text);
                                                                            swal("انجام شد", '', 'success');
                                                                        } else {
                                                                            swal("خطا", "این درخواست انجام نشد", "error");
                                                                        }
                                                                        $('#smallModal').modal('hide');
                                                                    });
                                                                } else {
                                                                    $('#smallModal').modal('hide');
                                                                }
                                                            });
                                                        }


                                                    });
                                                };


                                                let AddStatus = function (b) {
                                                    ID = b.attr('data-id');
                                                    btn = b;
                                                    $('#smallModal').modal({backdrop: "static"});
                                                };


                                                let ShowLocation = function (btn) {
                                                    let location = btn.attr('data-value');
                                                    let loc = LatLong(location);
                                                    if (loc == null) {
                                                        swal("خطا", "وارد نشده است.", "error");
                                                    } else {
                                                        moveToLocation(loc[0], loc[1], 17);
                                                    }
                                                };

                                                let AddAgent = function (btn) {
                                                    let request_id = btn.attr('data-id');

                                                    let model = $('#model-select-agent');
                                                    model.modal({backdrop: "static"});

                                                    let body = model.find('div.modal-body');

                                                    body.find('div.loading').fadeIn('fast');
                                                    body.find('div.content-agents').fadeOut('fast', function () {
                                                        body.find('div.content-agents').append().empty();
                                                        LoadData({
                                                            request: 'proxy',
                                                            object: {},
                                                            action: 'recyclingController',
                                                            'header-type': 'load-agent'
                                                        }, null, false, function (data) {
                                                            if (data.length > 0) {
                                                                body.find('div.loading').fadeOut("fast", function () {
                                                                    body.find('div.content-agents').empty().append(data);
                                                                    body.find('div.content-agents').fadeIn("fast");


                                                                    body.find('div.content-agents')
                                                                        .find('button.model-option-agent-select')
                                                                        .unbind().bind('click, tap', function (e) {
                                                                        let id = $(this).attr('data-code');
                                                                        let text = $(this).attr('data-text');
                                                                        swal({
                                                                            title: 'اخطار',
                                                                            text: 'ویرایش شود؟',
                                                                            type: "warning",
                                                                            showCancelButton: true,
                                                                            confirmButtonColor: "#DD6B55",
                                                                            confirmButtonText: "بله ",
                                                                            cancelButtonText: "نه ",
                                                                            closeOnConfirm: false,
                                                                            closeOnCancel: true
                                                                        }, function (isConfirm) {
                                                                            if (isConfirm) {
                                                                                LoadData({
                                                                                    request: 'proxy',
                                                                                    object: {
                                                                                        request: request_id,
                                                                                        agent: id
                                                                                    },
                                                                                    action: 'recyclingController',
                                                                                    'header-type': 'add-agent-for-request'
                                                                                }, null, false, function (data) {
                                                                                    if (parseInt(data) === 1) {
                                                                                        btn.text(text);
                                                                                        swal("انجام شد", '', 'success');
                                                                                    } else {
                                                                                        swal("خطا", "این درخواست انجام نشد", "error");
                                                                                    }
                                                                                    $('#model-select-agent').modal('hide');
                                                                                });
                                                                            } else {
                                                                                $('#model-select-agent').modal('hide');
                                                                            }
                                                                        });


                                                                    });

                                                                });
                                                            } else {
                                                                swal("خطا", "این درخواست انجام نشد", "error");
                                                                model.modal('hide');
                                                            }
                                                        });

                                                    });
                                                };

                                            });

                                            /**
                                             * @return {null}
                                             */
                                            let LatLong = function (myStr) {
                                                if (myStr.length > 0) {
                                                    let f = myStr.indexOf('(') + 1;
                                                    let l = myStr.indexOf(')');
                                                    let subStr = myStr.substring(f, l);
                                                    subStr = subStr.split(',');
                                                    return subStr;
                                                } else {
                                                    return null;
                                                }
                                            };

                                            let initGoogleMap = function (location = null) {
                                                if (Map == null) {
                                                    Map = new google.maps.Map($('#google-map')[0], {
                                                        center: new google.maps.LatLng(33, 55),
                                                        zoom: 5
                                                    });
                                                    // google.maps.event.addListener(Map, 'click', function (event) {
                                                    //     addMarker(event.latLng);
                                                    // });
                                                }

                                                try {
                                                    if (location == null) {
                                                        //  moveToLocation(33, 55, 5);
                                                    } else {
                                                        let loc = location.split(',');
                                                        if (loc.length === 2) moveToLocation(loc[0].replace("(", ''), loc[1].replace(")", ''), 5);
                                                    }
                                                } catch (e) {
                                                    console.log(e);
                                                }
                                            };
                                            let singleMarker, Map = null;


                                            let addMarker = function (latLng) {
                                                //if marker exists, erase marker
                                                if (singleMarker) {
                                                    singleMarker.setMap(null);
                                                }
                                                singleMarker = new google.maps.Marker({
                                                    position: latLng, //mouse click position
                                                    map: Map,
                                                    draggable: false,
                                                    icon: "http://www.google.com/mapfiles/marker_green.png"
                                                });
                                            };
                                            let moveToLocation = function (lat, lng, zoom) {
                                                let center = new google.maps.LatLng(lat, lng);
                                                // // using global variable:
                                                Map.setZoom(zoom);
                                                Map.panTo(center);
                                                addMarker(center);
                                            };
                                            initGoogleMap();


                                        }(jQuery));


                                    </script>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- #END# Exportable Table -->
        <!-- #END# Advanced Form Example With Validation -->
    </div>
</div>

<!-- Form -->
<div class="content-animation animated">
    <div class="row clearfix fBTitrBold ">
        <div class="row clearfix text-center">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                <div class="card ">
                    <div class="header">
                        <h2>
                            نقشه
                        </h2>
                    </div>
                    <div class="body ">
                        <div class="row">
                            <div class="btn btn-lg btn-info full_width " id="google-map"
                                 style="height: 350px"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="smallModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm clearfix fBTitrBold" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="smallModalLabel">
                    <center>وضعیت</center>
                </h4>
            </div>
            <div class="modal-body" dir="rtl">
                <?php
                $query = "SELECT `name`, `code` FROM `app_recycling_system` WHERE `key` LIKE ? AND `code`!=0";
                $status = $DAL->cSelect($query, array('s' => 'request_status'));
                foreach ($status as $s) {
                    if ($s['code'] == 1) echo '<button data-code="' . $s['code'] . '" type="button" data-color="deep-purple" class="model-option-status btn btn-block bg-deep-purple waves-effect"><h2>' . $s['name'] . '</h2></button>';
                    if ($s['code'] == 2) echo '<button data-code="' . $s['code'] . '" type="button" data-color="light-blue" class="model-option-status btn btn-block bg-light-blue waves-effect"><h2>' . $s['name'] . '</h2></button>';
                    if ($s['code'] == 3) echo '<button data-code="' . $s['code'] . '" type="button" data-color="deep-orange" class="model-option-status btn btn-block bg-deep-orange waves-effect"><h2>' . $s['name'] . '</h2></button>';
                    if ($s['code'] == 4) echo '<button data-code="' . $s['code'] . '" type="button" data-color="brown" class="model-option-status btn bg-brown btn-block waves-effect"><h2>' . $s['name'] . '</h2></button>';
                }
                ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link waves-effect" data-dismiss="modal">بستن</button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="model-select-agent" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg clearfix fBTitrBold" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    <center>انتخاب کنید.</center>
                </h4>
            </div>
            <div class="modal-body" dir="rtl">
                <div class="loading" dir="ltr">
                    <center>
                        <div class="preloader pl-size-xl">
                            <div class="spinner-layer">
                                <div class="circle-clipper left">
                                    <div class="circle"></div>
                                </div>
                                <div class="circle-clipper right">
                                    <div class="circle"></div>
                                </div>
                            </div>
                        </div>
                    </center>
                </div>
                <div class="content-agents">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link waves-effect" data-dismiss="modal">بستن</button>
            </div>
        </div>
    </div>
</div>

<!-- Form -->
<div class="content-animation animated">
    <div class="row clearfix fBTitrBold ">
        <div class="row clearfix text-center">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
                <div class="card ">
                    <div class="header">
                        <h2>
                            مسئول بازیافت
                        </h2>
                    </div>
                    <div class="body ">
                        <div class="row">
                            <div class="col-md-12" dir="ltr">
                                <div class="table-responsive text-center p-t-20 align-center no-overflow-y no-overflow-x">
                                    <table class="table-responsive table text-center table-profile
                                                    table-bordered table-striped table-hover dataTable js-exportable-recycling full_width"
                                           style="overflow-y: hidden">
                                        <thead>
                                        <tr class="text-center">
                                            <th class="text-center border-color-black">فعالیت ها</th>
                                            <th class="text-center border-color-black">وضعیت</th>
                                            <th class="text-center border-color-black">مسئول بازیافت</th>
                                            <th class="text-center border-color-black">شماره مبایل</th>
                                            <th class="text-center border-color-black">شماره ملی</th>
                                            <th class="text-center border-color-black">نام و نام خانوادگی</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php

                                        $query = "SELECT `ID`, `pNumber` as `mobile`,CONCAT(`fName`, ' ', `lName`) as `fullName`, `pNC` as `nc`,
                                        (SELECT `app_agent_recycling_system`.`is_active` FROM `app_agent_recycling_system` WHERE `agent_id`=`app_acceptor_profile`.`ID` ) as is_active ,
                                        (SELECT IF (COUNT(*)>0,TRUE,FALSE) FROM `app_agent_recycling_system` WHERE `agent_id`=`app_acceptor_profile`.`ID` ) as is_recycling ,
                                        (SELECT COUNT(*) FROM `app_recycling_request_system` WHERE `recycling_agent_id`=`app_acceptor_profile`.`ID`) as `active`                                    
                                        FROM `app_acceptor_profile` ORDER BY `is_recycling` and `nc` DESC ";
                                        $select = $DLA->cSelect($query);

                                        if ($select) {
                                            foreach ($select as $row) {
                                                echo "<tr itemid='" . $row['ID'] . "' dir='rtl'>" .
                                                    CreateButton($row) .
                                                    "<td>" . $row['mobile'] . "</td>" .
                                                    "<td>" . $row['nc'] . "</td>" .
                                                    "<td>" . $row['fullName'] . "</td>" .
                                                    "</tr>";
                                            }
                                        } else {
                                            echo "<tr><td colspan=4'>موردی یافت نشد</td></tr>";
                                        }

                                        function CreateButton($row)
                                        {


                                            $html = "";


                                            $html .= "<td>";
                                            if ($row['is_recycling'] == 1) {
                                                $html .= '<button class="btn btn-success btn-lg btn-block waves-effect" type="button"> مورد <span class="badge">' . $row['active'] . '</span></button>';
                                            } else {
                                                $html .= "<div class='action-area'>عضو نیست.</div>";
                                            }


                                            $html .= "</td>";


                                            $html .= "<td>";
                                            if ($row['is_recycling'] == 1) {
                                                if ($row['is_active'] == 1) $html .= "<button class='btn btn-success btn-block waves-effect wave-success option-recycling ' data-action='change-state' data-status='1'> فعال </button>";
                                                else $html .= "<button class='btn btn-warning btn-block waves-effect wave-success option-recycling' data-action='change-state' data-status='0'> غیر فعال </button>";
                                            } else {
                                                $html .= "<div class='status-area'>عضو نیست.</div>";
                                            }
                                            $html .= "</td>";


                                            $html .= "<td>";
                                            if ($row['is_recycling'] == 1) $html .= "<button class='btn btn-success btn-block waves-effect wave-success option-recycling' data-action='remove-agent'> بلی </button>";
                                            else $html .= "<button class='btn btn-danger btn-block waves-effect wave-success option-recycling' data-action='add-agent'> خیر </button>";

                                            $html .= "</td>";

                                            return $html;
                                        }


                                        ?>
                                        </tbody>
                                        <tfoot>
                                        <tr class="text-center">
                                            <th class="text-center border-color-black">فعالیت ها</th>
                                            <th class="text-center border-color-black">وضعیت</th>
                                            <th class="text-center border-color-black">مسئول بازیافت</th>
                                            <th class="text-center border-color-black">شماره مبایل</th>
                                            <th class="text-center border-color-black">شماره ملی</th>
                                            <th class="text-center border-color-black">نام و نام خانوادگی</th>
                                        </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- #END# Exportable Table -->
        <!-- #END# Advanced Form Example With Validation -->
    </div>
</div>
<script type="text/javascript">
    (function ($) {
        $(document).ready(function () {
            let event = function () {
                $(".js-exportable-recycling").find("button.option-recycling")
                    .unbind().bind("click, tap", function (e) {
                    let btn = $(this);
                    let action = btn.attr('data-action');
                    let ID = btn.closest('tr').attr('itemid');
                    switch (action) {
                        case 'remove-agent':

                            break;
                        case 'add-agent':
                            add_to_agent(btn, ID, btn.closest('tr'));
                            break;
                        case 'change-state':
                            change_status(btn, ID);
                            break;
                        default:
                            break;
                    }
                });
            };
            $('.js-exportable-recycling').DataTable({
                responsive: true,
                "language": {
                    "lengthMenu": "Display _MENU_ records per page",
                    "zeroRecords": " چیزی یافت نشد",
                    "info": "نمایش از _START_ تا _END_ در _TOTAL_ رکورد",
                    "infoEmpty": "<center>رکوردی پیدا نشد</center>",
                    "infoFiltered": "(filtered from _MAX_ total records)",
                    "paginate": {
                        "next": "بعدی",
                        "previous": "قبلی"
                    }
                },
                "fnInfoCallback": function (oSettings, iStart, iEnd, iMax, iTotal, sPre) {
                    event();
                },
                "fnDrawCallback": function (oSettings) {
                    event();
                }
            });


            let add_to_agent = function (btn, id, parent) {
                swal({
                    title: 'اخطار',
                    text: 'این کاربر اضافه شود؟',
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "بله ",
                    cancelButtonText: "نه ",
                    closeOnConfirm: false,
                    closeOnCancel: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        LoadData({
                            request: 'proxy',
                            object: {
                                agent: id
                            },
                            action: 'recyclingController',
                            'header-type': 'add-agent'
                        }, null, false, function (data) {
                            if (parseInt(data) === 1) {
                                if (btn.hasClass('btn-danger')) {
                                    btn.removeClass('btn-danger').addClass('btn-success');
                                    btn.text("بلی");
                                    btn.attr('data-action', 'remove-agent')
                                } else {
                                    btn.removeClass('btn-success').addClass('btn-danger');
                                    btn.text("خیر");
                                    btn.attr('data-action', 'add-agent');
                                }
                                parent.find('div.status-area').empty().append("<button class='btn btn-warning btn-block waves-effect wave-success option-recycling' data-action='change-state' data-status='0'> غیر فعال </button>")
                                parent.find('div.action-area').empty().append('<button class="btn btn-success btn-lg btn-block waves-effect" type="button"> مورد <span class="badge">0</span></button>');
                                event();
                                swal("انجام شد", '', 'success');
                            } else {
                                swal("خطا", "این درخواست انجام نشد", "error");
                            }
                        });
                    }
                });
            };

            let change_status = function (btn, id) {
                let status = btn.attr('data-status');
                status = (status === '1' ? '0' : '1');
                swal({
                    title: 'اخطار',
                    text: 'ویرایش وضعیت کاربر',
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "بله ",
                    cancelButtonText: "نه ",
                    closeOnConfirm: false,
                    closeOnCancel: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        LoadData({
                            request: 'proxy',
                            object: {
                                agent: id,
                                status: status
                            },
                            action: 'recyclingController',
                            'header-type': 'change-agent-status'
                        }, null, false, function (data) {
                            if (parseInt(data) === 1) {

                                if (btn.hasClass('btn-warning')) {
                                    btn.removeClass('btn-warning').addClass('btn-success');
                                    btn.text("فعال")
                                } else {
                                    btn.removeClass('btn-success').addClass('btn-warning');
                                    btn.text("غیر فعال")
                                }
                                btn.attr('data-status', status);
                                swal("انجام شد", '', 'success');
                            } else {
                                swal("خطا", "این درخواست انجام نشد", "error");
                            }
                        });
                    }
                });
            };


            event();

        });
    }(jQuery));
</script>
