<?php
/**
 * Created by PhpStorm.
 * User: Kavand
 * Date: 5/8/2019
 * Time: 1:13 AM
 */

$object = $request['object'];
switch ($request['header-type']) {
    case 'add-profile':
        $query = "INSERT INTO `app_acceptor_profile` (fName, lName, pNumber, pNC) VALUES ('{$object['fName']}','{$object['lName']}','{$object['pNumber']}','{$object['pNC']}')";
        $ID = $DAL->DoCommandID($query);
        if ($ID) {
            echo $ID;
        } else {
            echo 0;
        }
        break;
    case 'remove-profile':
        $query = "DELETE FROM `app_acceptor_profile`WHERE `ID`='{$object['id']}'";
        echo($DAL->DoCommand($query) ? '1' : '0');
        break;
    case 'add-acceptor':
        switch ($object['mode']) {
            case 'direct':
                $query = 'INSERT INTO `app_acceptor_list` ';
                $location = $object['sLocation'];
                $location = str_replace('(', '', $location);
                $location = str_replace(')', '', $location);
                $location = explode(',', $location);
                $lat = $location[0];
                $lng = $location[1];
                $query .= '(`profile_id`, `sName`, `sGuild`, `sNumber`, `sPhoto`, `sAP`, `sLocation`, `sAddress`, `sStart`, `sEnd`, `sDiscount`, `sTelegram`, `sSite`, `sInstagram`, `sFacebook`, `Lat`, `Lng`, `sInstallments`, `province`, `county`)';
                $query .= ' VALUES ';
                $query .= "(" . $object['profileKey'] . ", '{$object['sName']}', '{$object['sGuild']}', '{$object['sNumber']}', '{$object['sPhoto']}', '{$object['sAP']}', '{$object['sLocation']}', '{$object['sAddress']}', '{$object['sStart']}', '{$object['sEnd']}', '{$object['sDiscount']}', '{$object['sTelegram']}', '{$object['sSite']}', '{$object['sInstagram']}', '{$object['sFacebook']}',  '{$lat}', '{$lng}', '{$object['sInstallments']}', '{$object['province']}', '{$object['county']}')";
                echo($DLA->DoCommand($query) ? '1' : '0');
                break;
            case 'limit':
                /*$pageId = $object['page-id'];
                $pageMode = $object['page-mode'];
                if (isset($pageId) AND isset($pageMode)) {
                    $select = $DLA->Select("SELECT * FROM app_client_register WHERE `ID`='$pageId'");
                    if ($select AND $select[0]['Mode'] == "2") {
                        $query = 'INSERT INTO `app_acceptor_list`';
                        $location = $object['sLocation'];
                        $location = str_replace('(', '', $location);
                        $location = str_replace(')', '', $location);
                        $location = explode(',', $location);
                        $lat = $location[0];
                        $lng = $location[1];
                        $query .= '(`profile_id`, `sName`, `sGuild`, `sNumber`, `sPhoto`, `sAP`, `sLocation`, `sAddress`, `sStart`, `sEnd`, `sDiscount`, `sTelegram`, `sSite`, `sInstagram`, `sFacebook`, `Lat`, `Lng`, `IsActive`, `IsApp`, `visitor_id`)';
                        $query .= ' VALUES ';
                        $query .= "('{'{$object['']}', '{$object['sName']}', '{$object['sGuild']}', '{$object['sNumber']}', '{$object['sPhoto']}', '{$object['sAP']}', '{$object['sLocation']}', '{$object['sAddress']}', '{$object['sStart']}', '{$object['sEnd']}', '{$object['sDiscount']}', '{$object['sTelegram']}', '{$object['sSite']}', '{$object['sInstagram']}', '{$object['sFacebook']}',  '{$lat}', '{$lng}',0,1,'{$pageId}')";
                        echo($DLA->DoCommand($query) ? '1' : '0');
                    } else {
                        echo 0;
                    }
                } else {*/
                echo 0;
                break;
            default:
                echo 0;
                break;
        }
        break;
    case 'load-acceptor':
        $object = $request['object'];
        $array = array();
        $id = "";
        $mode = 'direct';
        if (isset($object)) {
            $id = " WHERE `visitor_id`=" . $object['page-id'] . "";
            $mode = $object['mode'];
        }


        //182

        $select = $DLA->Select(
            "Select *,(
                SELECT count(ID) > 0
                FROM `app_guild_list`
                WHERE `ID` = `app_acceptor_list`.`sGuild` AND `app_guild_list`.`gActive`=1
            ) as `isExist` From `app_acceptor_list`;");


//        $select = $DLA->Select("Select * From `app_acceptor_list` " . $id);
        $table = array(
            'CopyOfBirthCertificate' => 'copy-shenasname',
            'CopyTheNationalCard' => 'copy-cart-meli',
            'CopyTheNationalCardBack' => 'copy-cart-meli-posht',
            'CopyBusinessLicense' => 'copy-javaz-kasb',
            'CopyTheBillForWaterOrGas' => 'copy-bargh-gaz-ab',
            'CopyTheFrontPageOfTheContract' => 'copy-gharardad'
        );
        $query = '';
        $empty = array();
        if ($select) {
            $counter = 0;
            foreach ($select as $row) {
                $array['error'] = 0;
                $array['ID'] = $row['ID'];
                $array['acceptor-code'] = $row['ID'];

                $array['profile_id'] = $row['profile_id'];

//        $array['/**********/'] = $row['/**********/'];
                $array['sName'] = $row['sName'];
                $array['sGuild'] = $row['sGuild'];
                $array['sNumber'] = $row['sNumber'];
                $array['sPhoto'] = $row['sPhoto'];
//        $array['/**********/'] = $row['/**********/'];
                $array['sAP'] = $row['sAP'];
                $array['sLocation'] = $row['sLocation'];
                $array['sAddress'] = $row['sAddress'];
//        $array['/**********/'] = $row['/**********/'];
                $array['sStart'] = $row['sStart'];
                $array['sEnd'] = $row['sEnd'];
                $array['sDiscount'] = $row['sDiscount'];
                $array['sInstallments'] = $row['sInstallments'];
//        $array['/**********/'] = $row['/**********/'];
                $array['sTelegram'] = $row['sTelegram'];
                $array['sSite'] = $row['sSite'];
                $array['sInstagram'] = $row['sInstagram'];
                $array['sFacebook'] = $row['sFacebook'];

                $array['province'] = $row['province'];
                $array['county'] = $row['county'];

//        $array['img'] = '<a href="javascript:void(0);" class="thumbnail"><img style="width: 90px!important;" src="' . ConvertStringToImageArray($row['aPlaceUrlImage'], true) . '" class="img-responsive"></a>';

//                $array['full-name'] = $row['fName'] . ' ' . $row['lName'];
                $profile = $DLA->Select("SELECT concat(`fName`, ' ', `lName`) as `full-name` FROM `app_acceptor_profile` WHERE ID = '{$array['profile_id']}'");
                if ($profile) $array['full-name'] = $profile[0]['full-name'];
                else$array['full-name'] = 'کاربری وجود ندارد';

                $array['img'] = ImageSlider($counter, $row['sPhoto']);
                $array['button-edit'] = LoadOptionEdit($row['ID'], $row['IsActive'], $counter, $type, $row['IsApp'], $mode, !$row['isExist']);
                $array['document'] = array(
                    'copy-shenasname' => '',
                    'copy-cart-meli' => '',
                    'copy-cart-meli-posht' => '',
                    'copy-javaz-kasb' => '',
                    'copy-bargh-gaz-ab' => '',
                    'copy-gharardad' => '',
                );
                if ($mode == 'limit') {
                    $query = "SELECT `CopyOfBirthCertificate` AS 'copy-shenasname',
                      `CopyTheNationalCard` AS 'copy-cart-meli',
                      `CopyTheNationalCardBack` AS 'copy-cart-meli-posht',
                      `CopyBusinessLicense` AS 'copy-javaz-kasb',
                      `CopyTheBillForWaterOrGas` AS 'copy-bargh-gaz-ab',
                      `CopyTheFrontPageOfTheContract` AS 'copy-gharardad' FROM `app_acceptor_document` WHERE `idFor`='{$row['ID']}'";

                    $document = $DLA->Select($query);
                    if ($document AND count($document) == 1) {
                        $array['document'] = $document[0];
                    }
                }
                if ($mode == 'direct') {
                    $array['terminal'] = '<button data-id="' . $row['ID'] . '" class="btn btn-success waves-effect" data-action="acceptor-terminal">اضافه کردن کد پذیرنده</button>';
                }
                $array['index'] = $counter;
                $array['counter'] = $counter + 1;
                $empty[] = $array;
                $counter += 1;
            }
            echo json_encode($empty, JSON_UNESCAPED_UNICODE);
        } else {
            echo '[]';
        }
        break;
    case 'active-acceptor':
        echo($DLA->DoCommand("UPDATE `app_acceptor_list` SET `IsActive`='{$object['show']}' where `ID`='{$object['id']}'"));
        break;
    case 'delete-acceptor':
        echo($DLA->DoCommand("DELETE FROM `app_acceptor_list` WHERE `ID`='{$object['id']}'") ? '1' : '0');
        break;
    case 'edit-acceptor':

        $request = $request['object'];
        $query = "UPDATE `app_acceptor_list` SET ";
        $query .= "`profile_id`= '{$request['profileKey']}',";
        $query .= "`sName`= '{$request['sName']}',";
        $query .= "`sGuild`= '{$request['sGuild']}',";
        $query .= "`sNumber`= '{$request['sNumber']}',";
        $query .= "`sPhoto`= '{$request['sPhoto']}',";
        $query .= "`sAP`= '{$request['sAP']}',";
        $query .= "`sLocation`= '{$request['sLocation']}',";
        $query .= "`sAddress`= '{$request['sAddress']}',";
        $query .= "`sStart`= '{$request['sStart']}',";
        $query .= "`sEnd`= '{$request['sEnd']}',";
        $query .= "`sDiscount`= '{$request['sDiscount']}',";
        $query .= "`sTelegram`= '{$request['sTelegram']}',";
        $query .= "`sSite`= '{$request['sSite']}',";
        $query .= "`sInstagram`= '{$request['sInstagram']}',";
        $query .= "`sFacebook`= '{$request['sFacebook']}',";
        $query .= "`sInstallments`= '{$request['sInstallments']}',";

        $query .= "`province`= '{$request['province']}',";
        $query .= "`county`= '{$request['county']}',";

        $location = $request['sLocation'];
        $location = str_replace('(', '', $location);

        $location = str_replace(')', '', $location);
        $location = explode(',', $location);

        $lat = $location[0];
        $lng = $location[1];
        $query .= "`Lat`= '{$lat}',";
        $query .= "`Lng`= '{$lng}',";
        $query .= "`IsApp`= '0'";
        $query .= " WHERE `ID`='{$request['id']}'";
        echo($DLA->DoCommand($query) ? '1' : '0');
        break;
    default:
        echo 0;
        break;
}

function LoadOptionEdit($ID, $f, $index, $type, $isAccept, $mode, $notExist = false)
{
    $html = '';
    $html .= ' <div class="btn-group-vertical " role="group" aria-label="Vertical button group">';
    if ($mode == 'direct') {
        $html .= '<button data-index="' . $index . '" class="btn btn-xs btn-danger waves-effect" data-mod="acceptor" data-action="delete-item" data-id="' . $ID . '">';
        $html .= '<i class="material-icons">delete_forever</i>';
        $html .= '</button>';
        if ($f == 0) {
            if ($type !== 'limit') {
                $html .= '<button data-index="' . $index . '" rel="tooltip" title="فعال/غیرفعال" data-mod="acceptor" data-action="show-item" data-id="' . $ID . '" data-value="1"';
            } else {
                $html .= '<div disabled ';
            }
            $html .= ' class="btn btn-xs waves-effect btn-warning"><i class="material-icons">visibility_off</i>';
        } else {
            if ($type !== 'limit') {
                $html .= '<button data-mod="acceptor" data-action="show-item" data-index="' . $index . '" rel="tooltip" title="فعال/غیرفعال" data-id="' . $ID . '" data-value="0"';
            } else {
                $html .= '<div disabled ';
            }
            $html .= ' class="btn btn-xs waves-effect btn-info"><i class="material-icons">visibility</i>';
        }
        if ($type !== 'limit') {
            $html .= '</button>';
        } else {
            $html .= '</div>';
        }
        $html .= '<button data-index="' . $index . '" class="btn btn-xs btn-success waves-effect" data-mod="acceptor" data-action="edit-item" data-id="' . $ID . '">';
        $html .= '<i class="material-icons">mode_edit</i>';
        $html .= '</button>';
    }

    if ($mode == 'limit') {
        $html .= '<button data-index="' . $index . '" data-action="add-document" class="btn btn-xs btn-success waves-effect" data-mod="acceptor" data-id="' . $ID . '">';
        $html .= ("اظافه کردن مدارک");
        $html .= '</button>';

    }
    $html .= '<button data-index="' . $index . '" class="btn btn-xs btn-' . ($isAccept === '0' ? 'info ' : 'warning ') . 'waves-effect" data-mod="acceptor" data-id="' . $ID . '">';
    $html .= ($isAccept === '0' ? "تایید شده" : "در انتظار");
    $html .= '</button>';
    $html .= '<button class="btn btn-xs btn-' . (!$notExist ? 'success ' : 'warning ') . 'waves-effect">';
    $html .= (!$notExist ? "قابل نمایش" : "غیر قابل نمایش");
    $html .= '</button>';

    $html .= '</div>';
    return $html;
}


function ImageSlider($id, $string = "")
{
    $return = '<div id="carousel-example-generic-' . $id . '" class="carousel slide" data-ride="carousel">';
    $return .= '<div class="carousel-inner" role="listbox">';
    $temp = '';
    if (strlen($string) > 0) {
        $array = ConvertStringToImageArray($string, false);
        if (count($array) > 0) {
            $counter = 0;
            foreach ($array as $url) {
                if ($counter == 0)
                    $temp .= SlideItem($url['url'], true);
                $temp .= SlideItem($url['url']);
                $counter += 1;
            }
        } else {
            $temp .= SlideItem($array['url']);
        }
    } else {
        $temp = SlideItem(defaultImage, true);
    }
    $return .= $temp;
    $return .= '</div>';
    $return .= '<a class="left carousel-control" href="#carousel-example-generic-' . $id . '" role="button" data-slide="prev">';
    $return .= '<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>';
    $return .= '<span class="sr-only">Previous</span>';
    $return .= '</a>';
    $return .= '<a class="right carousel-control" href="#carousel-example-generic-' . $id . '" role="button" data-slide="next">';
    $return .= '<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>';
    $return .= '<span class="sr-only">Next</span>';
    $return .= '</a>';
    return $return;
}

function SlideItem($url, $active = false)
{
    $activeItem = '';
    $activeItem .= '<div style="width: 270px!important; height:90px!important;" class="item text-center' . ($active ? ' active ' : "") . '">';
    $activeItem .= '<center><img src="' . $url . '"/></center>';;
    $activeItem .= '</div>';
    return $activeItem;
}
