<?php 
	ini_set('display_errors', '1');
	//error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
	error_reporting(E_ALL);
	require (CONFIG.'dbconnect.php');
	require (PAGE_CONTENT.$PageContent);

	global $SA;

	if(isset($_COOKIE["WizSellKrugerrand"])){
		$data = json_decode($_COOKIE['WizSellKrugerrand']);
		$data = json_decode(json_encode($data), True);
	}
	else
		$data = null;
	

	//20190617 - Change Sell KR and Buy KR pages to use new table web_retail_pricing. -Gael
	//$pdo = $SA->query("SELECT GoldPriceZARPerOz FROM web_gold_pricing ORDER BY ID DESC LIMIT 1");
	$pdo = $SA->query("SELECT GoldPriceZARPerOz, SellToUsSpread FROM web_retail_pricing ORDER BY ID DESC LIMIT 1");
	$pdo->execute();
	$results = $pdo->fetch();
	
	$sellPrice = round( $results['GoldPriceZARPerOz'] + ( $results['GoldPriceZARPerOz'] * $results['SellToUsSpread'] * 0.01 ) , 2);

	$oneOunce = number_format($sellPrice, 2, ".", ",");
	$oneHalfOunce = number_format(($sellPrice/2), 2, ".", ",");
	$oneQuarterOunce = number_format(($sellPrice/4), 2, ".", ",");
	$oneTenthOunce = number_format(($sellPrice/10), 2, ".", ",");

	$strOneOunce = "R ".$oneOunce;
	$strOneHalfOunce = "R ".$oneHalfOunce;
	$strOneQuarterOunce = "R ".$oneQuarterOunce;
	$strOneTenthOunce = "R ".$oneTenthOunce;

	$dblTotalCoinWeight = (isset($data["dblTotalCoinWeight"])) ? $data["dblTotalCoinWeight"] : 0;
	//$dblCurrentSellPrice = (isset($data["dblCurrentSellPrice"])) ? $data["dblCurrentSellPrice"] : 0;
	$dblTotalSellPrice = (isset($data["dblTotalSellPrice"])) ? $data["dblTotalSellPrice"] : 0;
	$sell_krugerrand_quantity = (isset($data["sell_krugerrand_quantity"])) ? $data["sell_krugerrand_quantity"] : 0;
	$sell_krugerrand_quantity_2=(isset($data["sell_krugerrand_quantity_2"])) ? $data["sell_krugerrand_quantity_2"] :0;
	$sell_krugerrand_quantity_3 =(isset($data["sell_krugerrand_quantity_3"]))?$data["sell_krugerrand_quantity_3"] :0;
	$sell_krugerrand_quantity_4 =(isset($data["sell_krugerrand_quantity_4"]))?$data["sell_krugerrand_quantity_4"] :0;
?>

<style type="text/css">
	.SellPrice p {
      padding:0; 
      margin:0;
      font-size: 16px;
      color:#B09068;
  	}
  	.tabs .tab a {
  		color: grey;
  	}
  	.tabs .tab a:hover {
  		color: #3b1c5f;
  	}

  	.tabs .tab a {
  		color: #3b1c5f;
  	}
</style>

<div id="<?php echo $pageID;?>" class="page-wrapper row">
	<form id="frmSellToUs">
		<div class="investment-comparison col s12 col " style="background-color: #f8f7fb;">
			<div class="content-wrap">
				<div class="row">
			    	<div class="col m12 s12">
              <div class='mt-element-step'>
                  <div class='row step-line'>
                    <div class='col m6 s6 mt-step-col done'>
                      <div class='mt-step-title' style="padding: 0;">
                        <a id='aStep_' style='text-decoration: none; color: #3b1c5f;' onclick='' href=''>Sell To Us</a>
                      </div>
                    </div>
                    <div class='col m6 s6 mt-step-col'>
                      <div class='mt-step-title' style="padding: 0;">
                        <a id='bStep_' style='text-decoration: none; color: #3b1c5f;' onclick='' href=''>Seller Details</a>
                      </div>
                    </div>
                  </div>
              </div>
			    	</div>
			  	</div>
			  	<div class="container">
					<!-- <h6 class="center-align intro-head-type alrightsansmedium"><?php //echo $bao_headCompare ;?></h6> -->
					<div class="row">
						<div class="col-md-10 " style="padding: 7px 0 0 0;">
							<b>Best Price</b> - We will buy your bullion Krugerrands from you at above market rates that are typically the best locally and internationally.
						</div>

						<div class="col-md-12 col-sm-12" style="padding: 7px 0 0 0;">
							<b>Safe and Secure</b> - We will meet with you at a highly secure location in Bedfordview and Cape Town to validate the Krugerrand/s and facilitate immediate payment to you via real-time EFT.
						</div>

						<div class="col-md-12 col-sm-12" style="padding: 7px 0 0 0;">
							<b>100% Confidentiality** </b> - The security and protection of your personal information is of utmost importance to us. We are licensed by the Financial Services Conduct Authority and subscribe to best practices regarding the protection of your personal information
						</div>
						<br>

            <span style="font-size: 11px;">*The percentage above market value will vary depending on market conditions.  The standard buyback rate is 2% more than the market value.</span><br>
            <span style="font-size: 11px;">**In terms of the FICA Act we will require 1) a copy of your identification and 2) proof of your residential address</span>
            <br><br>
						<div>
							<span class="krugerrand-price-info" style="">
								<p style="font-weight:bold;">Price indicator until 2pm <?php echo date('d F Y');  ?></p>
							</span>
							<table class="table" border="1">
								<thead>
									<tr>
										<th>KR size</th>
										<th>1 oz</th>
										<th>½ oz</th>
										<th>¼ oz</th>
										<th><span>&#8530;</span> oz</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>Price</td>
										<td><?php echo $strOneOunce; ?></td>
										<td><?php echo $strOneHalfOunce; ?></td>
										<td><?php echo $strOneQuarterOunce; ?></td>
										<td><?php echo $strOneTenthOunce; ?></td>
									</tr>
								</tbody>
							</table>
							<span class="krugerrand-price-info" style="">
								<p style='color:#3b1c5f; font-size: 12px;'>Prices may move up or down subject to changes in the gold price</p>
							</span>
							<br>
							<span class="krugerrand-price-info" style="">
								<p style='font-weight:bold; color:#3b1c5f; font-size: 17px;'>Try our personalised calculator below to see how much we will pay you for your Krugerrands.</p>
							</span>
							<div class='col s12 m12'>
                     	<input id='dblTotalCoinWeight' name="dblTotalCoinWeight" value="<?php echo $dblTotalCoinWeight; ?>" type='hidden' >
                     	<!-- <input id='dblCurrentSellPrice' name="dblCurrentSellPrice" value="<?php echo $dblCurrentSellPrice; ?>" type='hidden'> -->
                     	<input id='dblTotalSellPrice' name="dblTotalSellPrice" value="<?php echo $dblTotalSellPrice; ?>" type='hidden'>
                     	<table id='tblDenomination' class='highlight condense' style='font-family: Alright Sans;color:#3b1c5f;' width='100%'>
                        	<thead>
                           	<tr>
                              	<th>KR Size</th>
                              	<th>Quantity</th>
                              	<th style='text-align: right;'>Total Price per Krugerrand</th>
                           	</tr>
                        	</thead>
                        	<tbody>
                           	<tr>
                              	<td>1 oz Krugerrand</td>
                              	<td width='20%'>
                              		<input id='sell_krugerrand_quantity' name="sell_krugerrand_quantity" type='number' min='0' 
                              		value='<?php echo $sell_krugerrand_quantity; ?>' placeholder='Enter Sell Krugerrand Quantity for One Once' 
                                  onkeypress='return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && 
                                  event.charCode <= 57'
                              		onchange='calculateCoinWeight();' style='height: 20px;' >
                              	</td>
                              	<td id='lblOneOnce' width='40%'style='text-align: right;'>R1000</td>
                           	</tr>
                           	<tr>
                              	<td>½ oz Krugerrand</td>
                              	<td><input id='sell_krugerrand_quantity_2' name="sell_krugerrand_quantity_2" type='number' min='0' value='<?php echo $sell_krugerrand_quantity_2; ?>' placeholder='Enter Sell Krugerrand Quantity for One half Once' onchange='calculateCoinWeight();' style='height: 20px;'
                                  onkeypress='return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && 
                                  event.charCode <= 57'>
                              	</td>
                              	<td id='lblOneHalfOnce' style='text-align: right;'>R1000</td>
                           	</tr>
                             <tr>
                                 <td>¼ oz Krugerrand</td>
                                 <td><input id='sell_krugerrand_quantity_3' name="sell_krugerrand_quantity_3" type='number' min='0' value='<?php echo $sell_krugerrand_quantity_3; ?>' placeholder='Enter Sell Krugerrand Quantity for One quater Once' onchange='calculateCoinWeight();' style='height: 20px;'
                                  onkeypress='return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && 
                                  event.charCode <= 57'>
                                 </td>
                                 <td id='lblOneQuaterOnce' style='text-align: right;'>R1000</td>
                             </tr>
                           	<tr>
                                 <td>⅒ oz Krugerrand</td>
                                 <td><input id='sell_krugerrand_quantity_4' name="sell_krugerrand_quantity_4" type='number' min='0' value='<?php echo $sell_krugerrand_quantity_4; ?>' placeholder='Enter Sell Krugerrand Quantity for One tenth Once' 
                                  onchange='calculateCoinWeight();' style='height: 20px;'
                                  onkeypress='return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && 
                                  event.charCode <= 57'>
                                 </td>
                                 <td id='lblOneTenthOnce' style='text-align: right;'>R1000</td>
                           	</tr>
                        	</tbody>
                        	<tfoot>
                           	<tr>
                           		<th></th>
                                 <th style='font-size:12px; padding:5px; text-align:left;'>Total Oz</th>
                                 <th style='font-size:12px; padding:5px; text-align:right;'>Total Due To You</th>
                           	</tr>
                           	<tr>
                           		<td></td>
                              <td colspan="1"><span id='spanTotalCoinWeight' style="font-weight: bold;">0 Oz</span></td>
                              <td colspan="1" style='text-align: right;'><span id='spanTotalSellPrice' style="font-weight: bold;">0</span></td>
                           	</tr>
                        	</tfoot>
                     	</table>
			         	</div> 
						</div>
					</div>
				</div>
        <div class="row">
          <div class="col s10">
            <span class="krugerrand-price-info" style="">
              <p style='font-weight:bold; color:#3b1c5f;'>I understand that this quote is illustrative and that prices can change due to market movements.</p>
            </span>
          </div>
          <div class="col s2">
            <span class="krugerrand-price-info" style="padding: 0 20px 5px 106px;clear: both;float:right;">
              <a id="btnFormSellToUs" class="btn btn-success" style="background-color: #3b1c5f;">Proceed</a>
            </span>
          </div>
        </div>
			</div><!-- content wrap -->
		</div>
	</form>
</div><!--  page-wrapper  -->
<script>
	var SiteUrl = '<?php echo $SiteUrl ;?>';
   $(document).ready(function(){
    // $('#modal-02 .hero-head-type').html('');
    // $('#modal-02 .hero-txt-type').html("Dear valued Client, in response to the 'COVID-19 national lockdown' - we will be buying in Krugerrands from the public up until the close of business on Thursday 26 March 2020.<br>Buy-backs will resume once the national lockdown ceases. You may proceed to use our sell calculator during the 'lockdown period' to be added to the queue for an appointment once the lockdown ends. <br>  Please be assured of our dedicated service at all times. <br>  The SA Bullion Team.");
    // $('#modal-02 #mc_embed_signup').html('');

    
    // $('.demo02').show();
    // $('.demo02').trigger('click');
      calculateCoinWeight();
      $('#btnFormSellToUs').click(function(){
   		var inputs = $('#frmSellToUs').serializeArray();
   		var url = SiteUrl + "/helpers/ajaxfunctions.php?type=jsFormSellToUs";

			var data = {};
			$(inputs).each(function(index, obj){
			   data[obj.name] = obj.value;
			});

   		var validated = jsValidateSellToUsForm();
   		if(validated)
   		{
   			Cookies.set('WizSellKrugerrand', data, { expires: 1 });
   			window.location.href = SiteUrl+"/krugerrand/sell/index.php?seller-details";
	      }
   	});
   });

   function calculateCoinWeight()
   {
      var quantityOne = parseInt(document.getElementById('sell_krugerrand_quantity').value);
      var quantityTwo = parseInt(document.getElementById('sell_krugerrand_quantity_2').value);
      var quantityThree = parseInt(document.getElementById('sell_krugerrand_quantity_3').value);
      var quantityFour = parseInt(document.getElementById('sell_krugerrand_quantity_4').value);

      quantityOne = isNaN(quantityOne) ? 0 : quantityOne;
      quantityTwo = isNaN(quantityTwo) ? 0 : quantityTwo;
      quantityThree = isNaN(quantityThree) ? 0 : quantityThree;
      quantityFour = isNaN(quantityFour) ? 0 : quantityFour;

      var dblTotalCoinWeight = quantityOne + (quantityTwo/2) + (quantityThree/4) + (quantityFour/10);

      var span = document.getElementById('spanTotalCoinWeight');
      span.textContent = dblTotalCoinWeight+' Oz';


      $.get(SiteUrl+'/dashboard/api/calc/index.php?krugerrandAmount='+dblTotalCoinWeight+'&krugerrandCalc=true'+'&sellKrugerrand=true')
         .done(function (data) {
          var Myresponse = JSON.parse(data);
         	//alert(Myresponse.KrugerRandPriceZAR);
         if (Myresponse.success == true) 
 			{
            var strCurrentSellPrice = 'R ' + Myresponse.KrugerRandPriceZAR;
            var dblCurrentSellPrice = Myresponse.KrugerRandPriceZAR;
            var dblTotalSellPrice = Myresponse.KrugerRandTotalPriceZAR;

            //alert(dblTotalSellPrice);

            var sellPrice = Myresponse.KrugerRandPriceZAR.replace(',', '');

            var oneOunce = (sellPrice * quantityOne).toFixed(2);
            var oneHalfOunce   = ( (sellPrice) * (quantityTwo/2)   ).toFixed(2);
            var oneQuaterOunce = ( (sellPrice) * (quantityThree/4) ).toFixed(2);
            var oneTenthOunce  = ( (sellPrice) * (quantityFour/10) ).toFixed(2);

            var strOneOunce = 'R ' + addCommas(oneOunce);
            var strOneHalfOunce = 'R ' + addCommas(oneHalfOunce);
            var strOneQuaterOunce = 'R ' + addCommas(oneQuaterOunce);
            var strOneTenthOunce = 'R ' + addCommas(oneTenthOunce);

            $('#lblOneOnce').html(strOneOunce);
            $('#lblOneHalfOnce').html(strOneHalfOunce);
            $('#lblOneQuaterOnce').html(strOneQuaterOunce);
            $('#lblOneTenthOnce').html(strOneTenthOunce);

            $('#currentSellPrice').html(strCurrentSellPrice);
            $('#spanTotalSellPrice').html('R '+dblTotalSellPrice);
            $('#pTotalSellPrice').html('R '+dblTotalSellPrice);

            $('#dblTotalCoinWeight').val(dblTotalCoinWeight);
            //$('#dblCurrentSellPrice').val(dblCurrentSellPrice);
            $('#dblTotalSellPrice').val(dblTotalSellPrice);
         }
      });
   }

   function jsValidateSellToUsForm()
   {
   	var state = false;
     	if($('#dblTotalCoinWeight').val() == 0)
      {
         $('#dblTotalCoinWeight').css({'border-bottom': '1px solid #F44336', '-webkit-box-shadow': '0 1px 0 0 #F44336', 'box-shadow': '0 1px 0 0 #F44336' });
         swal('Please enter at least one of the Krugerrand quantity fields', '', 'warning');
         state = false;
      }else{
         $('#dblTotalCoinWeight').css({'border-bottom': '', '-webkit-box-shadow': '', 'box-shadow': '' });
         state = true;
     	}

     	return state;
   }
</script>
