<?php
session_start();
include("../include/config.php");
include("../include/simpleimage.php");
include("../include/functions.php"); 
validate_admin();

// Save Data
if($_REQUEST['submitForm']=='yes'){
    //Get inputs
    $title=mysqli_real_escape_string($GLOBALS['conn'],$_POST['title']);
    $shortdesp=mysqli_real_escape_string($GLOBALS['conn'],$_POST['shortdesp']);
    $discount=mysqli_real_escape_string($GLOBALS['conn'],$_POST['discount']);

    $obj->query("update $tbl_setting set food_popup_discount='$discount', food_popup_title = '$title', food_popup_short_desp = '$shortdesp' where id=1");
    $_SESSION['sess_msg']='Data updated successfully';   

    //stores
    if($_REQUEST["hdnTmpIDs"] != ''){
        $stores_arr = explode (",", $_REQUEST["hdnTmpIDs"]);

        foreach($stores_arr as $indx) {
            $img = $_REQUEST["hdnOldImg-" . $indx];
            $popUpID = $_REQUEST["hdnPopUpID-" . $indx];
            $order = $_REQUEST["hdnOrderNo-" . $indx];
            $sec = $_REQUEST["ddlSec-" . $indx];
            $store = $_REQUEST["ddlStore-" . $indx];

            if($_FILES['fileImg-' . $indx]['size']>0 && $_FILES['fileImg-' . $indx]['error']==''){
                $Image= new SimpleImage();
                $filename = $_FILES['fileImg-' . $indx]['name'];
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                
                $img=time()."-".$filename;

                // Upload to main website FTP
                if(SITE_URL==MAINSITE_URL || SITE_URL==UATSITE_URL ||
                    SITE_URL==DEVSITE_URL){
                    $conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");

                     if(SITE_URL==MAINSITE_URL)
                        $login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");
                     else if(SITE_URL==UATSITE_URL)
                        $login_status = ftp_login($conn_id, "adminftp@uat.quicklly.com", "7*sDL(Wx=yY3") or die("Error in FTP login");
                     else
                        $login_status = ftp_login($conn_id, "adminftp@dev.quicklly.com", "0Xz}qnTXQuhJ") or die("Error in FTP login");
    
                    $destination_file = "upload_images/food-popup/".$img;
                    $upload_status = ftp_put($conn_id, $destination_file, $_FILES['fileImg-' . $indx]['tmp_name'], FTP_BINARY);
                        
                    if (!$upload_status)
                        echo "Something went wrong, Contact to site administrator.";
                        
                    ftp_close($conn_id);
                }
                
                // Upload locally to admin
                move_uploaded_file($_FILES['fileImg-' . $indx]['tmp_name'],"../upload_images/food-popup/".$img);
                
                $Image->load("../upload_images/food-popup/".$img);	  
                $Image->resize(300,300);	  
                $Image->save("../upload_images/food-popup/".$img);	 
                
                CompressImage('../upload_images/food-popup/'.$img, '../upload_images/food-popup/'.$img, 50);
            }

            if($popUpID == "0") {
                $obj->query("   INSERT INTO tbl_food_popup (sectionid, storeid, display_order, img)
                                VALUES ($sec, $store, $order, '$img')"); 
            }
            else {
                $obj->query("   UPDATE   tbl_food_popup 
                                SET      sectionid = $sec, storeid = $store,
                                         img = '$img', display_order = $order
                                WHERE    id = $popUpID"); 
            }
        }
    }

    //Delete
    if($_REQUEST["hdnDelIDs"] != ''){
        $obj->query("   DELETE FROM tbl_food_popup 
                        WHERE  id IN (" . $_REQUEST["hdnDelIDs"] . ")"); 
    }
}    

// Get Data
$sql=$obj->query("select food_popup_discount, food_popup_title, food_popup_short_desp from $tbl_setting where id=1");
$result=$obj->fetchNextObject($sql);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo SITE_TITLE; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/admin.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.2.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<style>
    .clsTemplate {
        display: none;
    }

    .clsFP_Stores {
        padding: 0;
        margin: 0;
        padding-left: 15px;
        display: inline-block;
    }

        .clsFP_Stores .clsFP_Store {
            border: 1px solid #c8c8c8;
            padding: 7px;
            background-color: #f3f4f6;
        }

        .clsFP_Stores .clsFP_Store:not(:last-child) {
            margin-bottom: 10px;
        }

            .clsFP_Stores .clsFP_Store img {
                display: inline-table;
                vertical-align: top;
                width: 70px;
                height: 70px;
                background-size: contain;
                background-repeat: no-repeat;
                background-position: center center;
            }

            .clsFP_Stores .clsFP_Store .cntrls {
                margin-left: 5px;
                display: inline-table;
                vertical-align: top;
            }

                .clsFP_Stores .clsFP_Store .cntrls select:not(:first-child) {
                    margin-left: 5px;
                }

                .clsFP_Stores .clsFP_Store .cntrls input[type=file]{
                    display: block;
                    margin-top: 5px;
                }

                .clsFP_Stores .clsFP_Store .cntrls a.clsRemoveBtn {
                    margin-top: 5px;
                    display: inline-block;
                    width:18px;
                    height: 18px;
                    background-image: url(../images/del.png);
                    background-repeat: no-repeat;
                    background-size: contain;
                    background-position: center center;
                }

    a.clsAddBtn {
        background-color: #0971a2;
        color: #FFFFFF;
        font-family: Verdana, Arial, Helvetica, sans-serif;
        font-size: 12px;
        border-radius: 5px;
        text-decoration: none;
        outline: none;
        display: inline-block;
        padding: 3px 5px;
    }   

    .ui-state-highlight {
        height: 86px;
        border: 1px dashed #e5d262 !important;
    }
</style>
</head>
<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<?php include("header.php") ?>
<tr>
	<td align="right" class="paddRtLt70" valign="top">
		<table width="99%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				
				<td align="right" valign="top">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td align="left" valign="middle" class="headingbg bodr text14">
                                <em><img src="images/arrow2.gif" width="21" height="21" hspace="10" align="absmiddle" /></em>Admin: Manage Food Popup
                            </td>
						</tr>
						
						<tr>
							<td height="100" align="left" valign="top" bgcolor="#f3f4f6" class="bodr">
                                <form name="frm" method="POST" enctype="multipart/form-data" action="" onsubmit="return validate(this)">
                                    <input type="hidden" name="submitForm" value="yes" />
                                    <input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
                                    <input type="hidden" name="hdnDelIDs" id="hdnDelIDs" value="">    
                                    <input type="hidden" name="hdnDelImgs" id="hdnDelImgs" value=""> 
                                    <input type="hidden" name="hdnTmpIDs" id="hdnTmpIDs" value="">

                                    <table width="100%" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center" colspan="2" class="paddRt14 paddBot11">
                                            <font color="#FF0000"><strong><?php echo $_SESSION['sess_msg']; $_SESSION['sess_msg']='';?></strong></font></td>
                                        </tr>
                                        <tr>
                                            <td width="18%" align="right" class="paddBot11 paddRt14">&nbsp;</td>
                                            <td width="82%" align="left" class="paddBot11"></td>
                                        </tr>
                                        <tr>
                                            <td align="right" class="paddBot11 paddRt14"><strong>Title:</strong></td>
                                            <td align="left" class="paddBot11"><input name="title" type="text" id="title" maxlength="100" style="width: 400px;" value="<?php echo stripslashes($result->food_popup_title);?>" /></td>
                                        </tr>	
                                        <tr>
                                            <td align="right" class="paddBot11 paddRt14"><strong>Short Desp.:</strong></td>
                                            <td align="left" class="paddBot11"><input name="shortdesp" type="text" id="shortdesp" maxlength="100" style="width: 400px;" value="<?php echo stripslashes($result->food_popup_short_desp);?>" /></td>
                                        </tr>	
                                        <tr>
                                            <td align="right" class="paddBot11 paddRt14"><strong>Discount:<br>(Set to 0 turn off popup)</strong></td>
                                            <td align="left" class="paddBot11"><input name="discount" type="text" id="discount" maxlength="2" style="width: 40px;text-align:right;" value="<?php echo stripslashes($result->food_popup_discount);?>" /> %</td>
                                        </tr>	
                                        <tr>
                                            <td align="right" class="paddBot11 paddRt14" style="vertical-align: top;"><strong>Stores:<br>(300 X 300px)(Not more than 100 KB):</strong></td>
                                            <td align="left" class="paddBot11">
                                                <p>Drag stores to arrange display order.<p>
                                                <ol class="clsFP_Stores">
                                                <?php
                                                    $stores = $obj->query(" SELECT * FROM tbl_food_popup order by display_order");
                                                    $TmpID = 1;

                                                    while($store = $obj->fetchNextObject($stores)){
                                                ?>
                                                    <li class="clsFP_Store" id="store-<?php echo $TmpID ?>">
                                                        <input type="hidden" name="hdnOrderNo-<?php echo $TmpID ?>" id="hdnOrderNo-<?php echo $TmpID ?>" value="<?php echo $TmpID ?>" class="order">
                                                        <input type="hidden" name="hdnPopUpID-<?php echo $TmpID ?>" id="hdnPopUpID-<?php echo $TmpID ?>" value="<?php echo $store->id ?>" class="id">
                                                        <input type="hidden" name="hdnOldImg-<?php echo $TmpID ?>" id="hdnOldImg-<?php echo $TmpID ?>" value="<?php echo $store->img ?>" class="old">
                                                        <input type="hidden" name="hdnTmpID-<?php echo $TmpID ?>" id="hdnTmpID-<?php echo $TmpID ?>" value="<?php echo $TmpID ?>" class="tmpid">

                                                        <img style="background-image: none, url('../upload_images/food-popup/<?php echo $store->img ?>');">

                                                        <div class="cntrls">
                                                            <select name="ddlSec-<?php echo $TmpID ?>" class="clsSelSec" onchange="getStores(this);" data-val="<?php echo $store->sectionid ?>">
                                                                <option value="">Select Section</option>
                                                                <option value="3">Food</option>
                                                                <option value="6">Tiffin</option>
                                                                <option value="4">Catering</option>
                                                            </select>

                                                            <select name="ddlStore-<?php echo $TmpID ?>" class="clsSelStore" data-val="<?php echo $store->storeid ?>">
                                                                <option value="">Select Store</option>
                                                            </select>

                                                            <input type="file" name="fileImg-<?php echo $TmpID ?>" onchange="setImg(this)" accept="image/jpeg, image/jpg, image/png">

                                                            <a href="javascript:void(0);" class="clsRemoveBtn" onclick="removeStore(this);"></a>
                                                        </div>
                                                    </li>
                                                <?php $TmpID = $TmpID + 1; } ?>
                                                </ol>

                                                <br><br>

                                                <a href="javascript:void(0);" class="clsAddBtn" onclick="addStore();">+ Add Store</a>
                                            </td>
                                        </tr>	
                                        <tr>
                                            <td align="right" class="paddRt14 paddBot11">&nbsp;</td>
                                            <td align="left" class="paddBot11">&nbsp;</td>
                                        </tr>
                                        <tr>
                                            <td width="18%" align="right" class="paddRt14 paddBot11">&nbsp;</td>
                                            <td width="82%" align="left" class="paddBot11">
                                                <input type="submit" name="submit" value="Update"  class="submit" onclick="return setData();" border="0"/>&nbsp;&nbsp;
                                            </td>
                                        </tr>
                                    </table>
                                </form>
							</td>
						</tr>
						
					</table>
				</td>
			</tr>
		</table>
	</td>
</tr>
<?php include('footer.php'); ?>
</table>

<div class="clsTemplate">
    <ol id="tempStore">
        <li class="clsFP_Store" id="{li_id}" style="display: none;">
            <input type="hidden" name="{0}" id="{1}" value="0" class="order">
            <input type="hidden" name="{2}" id="{3}" value="0" class="id">
            <input type="hidden" name="{4}" id="{5}" value="" class="old">
            <input type="hidden" name="{6}" id="{7}" value="{8}" class="tmpid">

            <img style="background-image: none, url('https://www.quicklly.com/images/no-img.jpg');">

            <div class="cntrls">
                <select name="{sel_sec}" onchange="getStores(this);">
                    <option value="">Select Section</option>
                    <option value="3">Food</option>
                    <option value="6">Tiffin</option>
                    <option value="4">Catering</option>
                </select>

                <select name="{sel_store}">
                    <option value="">Select Store</option>
                </select>

                <input type="file" name="{file_img}" onchange="setImg(this)" accept="image/jpeg, image/jpg, image/png">

                <a href="javascript:void(0);" class="clsRemoveBtn" onclick="removeStore(this);"></a>
            </div>
        </li>
    </div>
</div>

<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
    var lstStores = [
        <?php
            $storesArr=$obj->query("SELECT storeid, sectionid, storename FROM `stores` WHERE sectionid in (3,4,6) ORDER BY storename");
            while($store=$obj->fetchNextObject($storesArr)){
        ?>
                {
                    sid:'<?php echo$store->storeid ?>',
                    sname:'<?php echo$store->storename ?>',
                    section:[<?php echo$store->sectionid ?>]
                },
        <?php }?>
    ];

    function addStore(){
        var id = 1;

        var stores = $('.clsFP_Stores .clsFP_Store');
        if(stores.length > 0)
            id = parseInt(stores[stores.length - 1].id.substr(6)) + 1;

        var template = $('#tempStore').html();
        template = template.replace('{li_id}', 'store-' + id);
        template = template.replace('{0}', 'hdnOrderNo-' + id);
        template = template.replace('{1}', 'hdnOrderNo-' + id);
        template = template.replace('{2}', 'hdnPopUpID-' + id);
        template = template.replace('{3}', 'hdnPopUpID-' + id);
        template = template.replace('{4}', 'hdnOldImg-' + id);
        template = template.replace('{5}', 'hdnOldImg-' + id);
        template = template.replace('{6}', 'hdnTmpID-' + id);
        template = template.replace('{7}', 'hdnTmpID-' + id);
        template = template.replace('{8}', id);
        template = template.replace('{sel_sec}', 'ddlSec-' + id);
        template = template.replace('{sel_store}', 'ddlStore-' + id);
        template = template.replace('{file_img}', 'fileImg-' + id);
        $('.clsFP_Stores').append(template);

        var dvLast = $('.clsFP_Stores .clsFP_Store:last-child');

        $(dvLast).slideDown('normal', function () {
            $(this).find('select')[0].focus();
        });
    }

    function getStores(ddl){
        var ddlStore = $(ddl).next();
        $(ddlStore).find('option:not(:first-child)').remove();

        if(ddl.value != ''){
            var lstTmpStores = lstStores.filter(function (el) {return el.section.includes(parseInt(ddl.value));});

            if(lstTmpStores != null && lstTmpStores.length > 0){
                for (i = 0; i < lstTmpStores.length; i++) {
                    var option = document.createElement('option');
                    option.innerText = lstTmpStores[i].sname;
                    option.value = lstTmpStores[i].sid;
                    $(ddlStore).append(option);
                }
            }
        }
    }

    function removeStore(lnk){
        if(confirm('Remove store?')){
            var parent = $(lnk).closest('.clsFP_Store');

            var hdnID = $(parent).find('input[type=hidden]')[1];
            if (hdnID != undefined && hdnID.value != '0')
                $('#hdnDelIDs')[0].value += hdnID.value + ",";

            var hdnID = $(parent).find('input[type=hidden]')[2];
            if (hdnID != undefined && hdnID.value != '0')
                $('#hdnDelImgs')[0].value += hdnID.value + ",";

            $(lnk).closest('.clsFP_Store').slideUp('normal', function () {
                $(this).remove();
            });
        }
    }

    function setImg(fu){
        var dvImg = $(fu).parent().parent().find('img')[0];

        if (fu.files && fu.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                dvImg.style.backgroundImage = "url(" + e.target.result + ")";
            }

            reader.readAsDataURL(fu.files[0]);
        }
        else
            dvImg.style.backgroundImage = "none, url('https://www.quicklly.com/images/no-img.jpg')";
    }

    function validateData(){
        try{
            var ErrMsg = ''

            if ($('#title')[0].value == '') {
                ErrMsg += '- Enter title!\n';
                $('#title')[0].style.backgroundColor = '#ffe8e8';
            }
            else
                $('#title')[0].style.backgroundColor = 'transparent';

            if ($('#shortdesp')[0].value == '') {
                ErrMsg += '- Enter short description!\n';
                $('#shortdesp')[0].style.backgroundColor = '#ffe8e8';
            }
            else
                $('#shortdesp')[0].style.backgroundColor = 'transparent';

            if ($('#discount')[0].value == '') {
                ErrMsg += '- Enter discount!\n';
                $('#discount')[0].style.backgroundColor = '#ffe8e8';
            }
            else
                $('#discount')[0].style.backgroundColor = 'transparent';

            var stores = $('.clsFP_Stores .clsFP_Store');
            if(stores.length > 0) {
                var flgSec = false, flgStore = false, flgImg = false;
                for (var i = 0; i < stores.length; i++) {
                    var ddlSec = $(stores[i]).find('select')[0];
                    var ddlStore = $(stores[i]).find('select')[1];
                    var id = $(stores[i]).find('input[type=hidden]')[1];
                    var fileImg = $(stores[i]).find('input[type=file]')[0];

                    if (ddlSec.value == '') {
                        if (!flgSec) {
                            flgSec = true;
                            ErrMsg += '- Select section!\n';
                        }
                        $(ddlSec)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(ddlSec)[0].style.backgroundColor = 'transparent';

                    if (ddlStore.value == '') {
                        if (!flgStore) {
                            flgStore = true;
                            ErrMsg += '- Select store!\n';
                        }
                        $(ddlStore)[0].style.backgroundColor = '#ffe8e8';
                    }
                    else
                        $(ddlStore)[0].style.backgroundColor = 'transparent';

                    if (id.value == '0'){
                        if (fileImg.value == '') {
                            if (!flgImg) {
                                flgImg = true;
                                ErrMsg += '- Select image!\n';
                            }
                        }
                    }
                }
            }

            if (ErrMsg != '') {
                alert('Validation Error!\n' + ErrMsg);
                return false;
            }
            else
                return true;
        } catch (e) {
            alert('Validation Failed!\n');
            console.error(e.message);
            return false;
        }
    }

    function setData() {
        if(validateData()){
            $('#hdnTmpIDs')[0].value = '';

            var items = $(".clsFP_Stores .clsFP_Store")

            for (var i = 0; i < items.length; i++) {
                var hdnOrderNo = $(items[i]).find('input[type=hidden]')[0];
                hdnOrderNo.value = (i + 1);

                var hdnTmpID = $(items[i]).find('input[type=hidden]')[3];
                $('#hdnTmpIDs')[0].value += hdnTmpID.value + ',';
            }

            if(hdnTmpIDs.value != '')
                $('#hdnTmpIDs')[0].value =  $('#hdnTmpIDs').val().substr(0, $('#hdnTmpIDs').val().length - 1);

            if($('#hdnDelIDs').val() != '')
                $('#hdnDelIDs')[0].value =  $('#hdnDelIDs').val().substr(0, $('#hdnDelIDs').val().length - 1);

            return true;
        }
        else
            return false;
    }   

    $(".clsFP_Stores").sortable({
      placeholder: "ui-state-highlight"
    });
    $(".clsFP_Stores").disableSelection();

    setCombo();

    function setCombo(){
        var secs = $('.clsFP_Stores .clsFP_Store .clsSelSec');
        for (var i = 0; i < secs.length; i++) {
            secs[i].value = secs[i].dataset.val;
        }

        var stores = $('.clsFP_Stores .clsFP_Store .clsSelStore');
        for (var i = 0; i < stores.length; i++) {
            var ddlSec = $(stores[i]).parent().find('.clsSelSec')[0];

            if (lstStores != null) {
                var lstTmpStores = lstStores.filter(function (el) {return el.section.includes(parseInt(ddlSec.value));});

                if(lstTmpStores != null && lstTmpStores.length > 0){
                    for (var j = 0; j < lstTmpStores.length; j++) {
                        var option = document.createElement('option');
                        option.innerText = lstTmpStores[j].sname;
                        option.value = lstTmpStores[j].sid;
                        $(stores[i]).append(option);
                    }

                    stores[i].value = stores[i].dataset.val;
                }
            }
        }
    }

    setInputFilter(document.getElementById("discount"), function (value) {
        return /^-?\d*$/.test(value);
    });
    function setInputFilter(textbox, inputFilter) {
            ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function (event) {
                textbox.addEventListener(event, function () {
                    if (inputFilter(this.value)) {
                        this.oldValue = this.value;
                        this.oldSelectionStart = this.selectionStart;
                        this.oldSelectionEnd = this.selectionEnd;
                    } else if (this.hasOwnProperty("oldValue")) {
                        this.value = this.oldValue;
                        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                    } else {
                        this.value = "";
                    }
                });
            });
        }
</script>

</body>
</html>
