<?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']);
   

    //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];
			$heading = $_REQUEST["heading-" . $indx];
			$subheading = $_REQUEST["subheading-" . $indx];
			$rating = $_REQUEST["rating-" . $indx];
			$slug = $_REQUEST["slug-" . $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");
                    $login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");
					ftp_pasv($conn_id, true);
                    $destination_file = "upload_images/mealkit/new/".$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/mealkit/new/".$img);
                
                $Image->load("../upload_images/mealkit/new/".$img);	  
                $Image->resize(420,260);	  
                $Image->save("../upload_images/mealkit/new/".$img);	 
                
                CompressImage('../upload_images/mealkit/new/'.$img, '../upload_images/mealkit/new/'.$img, 50);
            }
     if($popUpID == "0") {
                $obj->query("INSERT INTO tbl_meal_kit_store (section_id, display_order, section_img, section_heading, section_subheading, section_rating,section_slug,type,status)
                                VALUES ($sec, $order, '$img','$heading','$subheading',$rating,'$slug',1,1)"); 
            }
            else {
                $obj->query("   UPDATE   tbl_meal_kit_store 
                                SET      section_id = $sec,
                                         section_img = '$img', display_order = $order, section_heading='$heading', section_subheading='$subheading', section_rating='$rating', section_slug='$slug', type=1, status=1
                                WHERE    id = $popUpID"); 
            }
        }
    }

    //Delete
    if($_REQUEST["hdnDelIDs"] != ''){
        $obj->query("   DELETE FROM tbl_meal_kit_store 
                        WHERE  id IN (" . $_REQUEST["hdnDelIDs"] . ")"); 
    }
}    


?>

<!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;
    }
input.textinputs {
    display: block;
    margin: 3px 0px;
}
    .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 Meal kit Store Page New Tab
                            </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>Tab Title:</strong></td>
                                            <td align="left" class="paddBot11"><input name="title" type="text" id="title" maxlength="100" style="width: 400px;" value="New" / readonly></td>
                                        </tr>	
                                       
                                        <tr>
                                            <td align="right" class="paddBot11 paddRt14" style="vertical-align: top;"><strong>Sections:<br>(420 X 260px)(Not more than 100 KB):</strong></td>
                                            <td align="left" class="paddBot11">
                                                <p>Drag Section to arrange display order.<p>
                                                <ol class="clsFP_Stores">
                                                <?php
                                                    $stores = $obj->query(" SELECT * FROM `tbl_meal_kit_store` where type=1 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->section_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/mealkit/new/<?php echo $store->section_img ?>');">

                                                        <div class="cntrls">
                                                            <select name="ddlSec-<?php echo $TmpID ?>" class="clsSelSec" data-val="<?php echo $store->section_id ?>">
                                                                <option value="">Select Section</option>
																<?php $sections = $obj->query("SELECT id,section_name FROM `tbl_section` where is_nationwide=1");
                                                   

                                                    while($section = $obj->fetchNextObject($sections)){?>
                                                                <option value="<?php echo $section->id;?>"><?php echo $section->section_name;?></option>
													<?php } ?>
                                                               
                                                            </select>
															<input type="text" class="textinputs" placeholder="Heading" name="heading-<?php echo $TmpID ?>" value="<?php echo $store->section_heading;?>">
															<input type="text" class="textinputs" placeholder="Sub Heading" name="subheading-<?php echo $TmpID ?>" value="<?php echo $store->section_subheading;?>">
															<input type="number" class="textinputs" placeholder="Rating" name="rating-<?php echo $TmpID ?>" value="<?php echo $store->section_rating;?>">
															<input type="text" class="textinputs" placeholder="Section Slug" name="slug-<?php echo $TmpID ?>" value="<?php echo $store->section_slug;?>">
                                                            <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 Section</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>
                    <?php $sections = $obj->query("SELECT id,section_name FROM `tbl_section` where is_nationwide=1");
                                                   

                                                    while($section = $obj->fetchNextObject($sections)){?>
                                                                <option value="<?php echo $section->id;?>"><?php echo $section->section_name;?></option>
													<?php } ?>
                </select>

                <input class="textinputs" type="text" placeholder="Heading" name="{heading}">
				<input class="textinputs" type="text" placeholder="Sub Heading" name="{subheading}">
				<input class="textinputs" type="number" placeholder="Rating" name="{rating}">
				<input type="text" class="textinputs" placeholder="Section Slug" name="{slug}">

                <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>
   

    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('{heading}', 'heading-' + id);
		  template = template.replace('{subheading}', 'subheading-' + id);
		   template = template.replace('{rating}', 'rating-' + id);
		    template = template.replace('{slug}', 'slug-' + 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 removeStore(lnk){
        if(confirm('Remove Section?')){
            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';

           

            

            var stores = $('.clsFP_Stores .clsFP_Store');
            if(stores.length > 0) {
                var flgSec = false, flgImg = false;
                for (var i = 0; i < stores.length; i++) {
                    var ddlSec = $(stores[i]).find('select')[0];
                    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 (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;
        }

        
    }


    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>
