<?= $this->extend('rs/template-user', $data); ?>
<?= $this->section('content'); ?>
<?php $this->include('rs/utils.php')?>


<style>
 select{width:250px!important;}
 input[type=text]{width:250px!important;}
 input[type=number]{width:250px!important;}
 input[type=date]{width:250px!important;}
 input[type=checkbox]{width:16px!important;}
 textarea{width:250px!important;}
 .custombtn{width:110px!important}
 #vin:invalid {border: 2px solid red;}
 #vin:invalid:focus {background-image: linear-gradient(pink, pink);
}
}
 
</style>


<div class="card shadow">
	<h6 class="m-0 font-weight-bold text-primary p-4">Car main details</h6>
	<div class="collapse show" id="collapsePrimary">
		<div class="card-body">
		
			<div class="row">
			  	<div class="card small" style="min-height:100px;margin:10px;width:25rem;">
				  <div class="card-body" style="min-height:100px;background:#E5EEFF;color:#000">
					<h5 class="card-title">Ad code:  <?php if (isset($code)) {echo formatCode($code);};?></h5>
						<p class="card-text">Ad creation date:	<?php if (isset($car)) {echo $car["created_at"];};?></p>
						<p class="card-text">Status:	
						<?php
								foreach ($statuses as $statitem)
								{
									if($car && $car['status']==$statitem['id'])
									{
										echo $statitem['status_name'];
										break;
									}
								
								}
						 ?>
						</p>
						
						<table cellpadding="5"><tr><td><button  onClick="saveAll(0)";  class="btn btn-primary btn-sm custombtn">Save draft</button></td><td><button  class="btn btn-info btn-sm custombtn" data-toggle="modal" data-target=".car-preview">Preview</button></td><td><button  class="btn btn-success btn-sm custombtn" onClick="saveAll(1)">Save&Publish</a></td></tr></table>
						</div>
					</div>
						
			</div>

				
				
				<form class="" action="/cars/edit/<?php echo $code;?>"  id="frmPrimary" name= id="frmPrimary" method="post" accept-charset="utf-8" enctype="multipart/form-data">
				
				<table class="table table-sm text-dark font-weight-bold small ml-1" style="width:400px">
   
				<tr>
					<td>Brand<span class='req'>*</span></td><td>
						
					   <select class="form-control-sm select2" name="brand" id="brand1"  required >
					   <option></option>
					   <?php
							foreach ($brands as $branditem)
							{
								if($car && $car['brand'] && $car['brand']==$branditem['brand_name'])
									echo '<option value="'.$branditem['brand_name'].'" selected>'.$branditem['brand_name'].'</option>';
								else
									echo '<option value="'.$branditem['brand_name'].'">'.$branditem['brand_name'].'</option>';
							}
					   ?>
					   </select></td><td></td>
				</tr>
			
			
				<tr>
					<td>Model<span class='req'>*</span></td><td>
						
					   <select class="form-control-sm select2" id="model" name ="model"  required>
					   <?php
							foreach ($models as $modelitem)
							{
								if($car && $car['model'] && $car['model']==$modelitem['model_name'])
									echo '<option value="'.$modelitem['model_name'].'" selected>'.$modelitem['model_name'].'</option>';
								else
									echo '<option value="'.$modelitem['model_name'].'">'.$modelitem['model_name'].'</option>';
							}
					   ?>
					   
					   </select></td><td></td>
				</tr>
				
				<tr>
				<td>
				   Price BGN gross<br>(without VAT)</td><td>
				   <input type="number" min="1" step="any" class="form-control" id="price_bgn" name ="price_bgn" tabindex=0 required 
				   value="<?php
						if ($car) {
							echo $car["price_bgn"];
						}
						?>">
				   </td><td></td>
				</tr>
				<tr>
					<td>Model description</td><td>
						
					   <input type="text" class="form-control" id="model_dec" name ="model_dec"   value="<?php
						if ($car) {
							echo $car["model_dec"];
						}
						?>">
					   </td><td></td>
				</tr>
			
				<tr>
					<td>Body type<span class='req'>*</span></td><td>
						
					   <select class="form-control-sm select2" name ="body_type"  required>
						<option <?php if($car && $car['body_type']=='Hatchback') echo 'selected'?>>Hatchback</option>
						<option <?php if($car && $car['body_type']=='Station wagon') echo 'selected'?>>Station wagon</option>
						<option <?php if($car && $car['body_type']=='Micro') echo 'selected'?>>Micro</option>
						<option <?php if($car && $car['body_type']=='MUV / monovolum') echo 'selected'?>>MUV / monovolum</option>
						<option <?php if($car && $car['body_type']=='Sedan') echo 'selected'?>>Sedan</option>
						<option <?php if($car && $car['body_type']=='Sports car / coupe') echo 'selected'?>>Sports car / coupe</option>
						<option <?php if($car && $car['body_type']=='Convertible / roadster') echo 'selected'?>>Convertible / roadster</option>
						<option <?php if($car && $car['body_type']=='SUV / off-road') echo 'selected'?>>SUV / off-road</option>
						<option <?php if($car && $car['body_type']=='Pickup') echo 'selected'?>>Pickup</option>
						<option <?php if($car && $car['body_type']=='Van cargo') echo 'selected'?>>Van cargo</option>
						<option <?php if($car && $car['body_type']=='Van passenger') echo 'selected'?>>Van passenger</option>

						</select></td><td></td>
				</tr>
				
				<tr>
					<td>Steering wheel<span class='req'>*</span></td><td>
						
					   <select class="form-control-sm select2" name ="steering_whell"  required>
						<option>Left</option>
						</select></td><td></td>
				</tr>
				
					
			
				<tr>
					<td>Cubic capacity (CC)<span class='req'>*</span></td><td>
						<input size="50" type="number" class="form-control" name="cubic_capacity"  style="width:170px!important" required value="<?php
						if ($car) {
							echo $car["cubic_capacity"];
						}
						?>"/></td><td></td>
				</tr>
				
				
				
			
				<tr>
					<td>Power<span class='req'>*</span></td><td>
						<table><tr><td style="padding-left:0">
						<input size="50" type="number" name="engine_power_hp" class="form-control" required style="width:170px!important" 
						value="<?php
						if ($car) {
							echo $car["engine_power_hp"];
						}
						?>"/>
						</td>
						<td>
						<select class="form-select form-select-sm" id ="unit" required style="float:left!important;width:70px!important">
							<option value="HP">HP</option>
							
						</select>
						</td>
						</tr>
						</table></td>
				</tr>
				
				<tr>
					<td>Fuel<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name ="fuel"  required>
						<option <?php if($car && $car['fuel']=='Diesel') echo 'selected'?>>Diesel</option>
						<option <?php if($car && $car['fuel']=='Gasoline') echo 'selected'?>>Gasoline</option>
						<option <?php if($car && $car['fuel']=='Biodiesel') echo 'selected'?>>Biodiesel</option>
						<option <?php if($car && $car['fuel']=='Electric 100%') echo 'selected'?>>Electric 100%</option>
						<option <?php if($car && $car['fuel']=='Ethanol') echo 'selected'?>>Ethanol</option>
						<option <?php if($car && $car['fuel']=='Natural gas') echo 'selected'?>>Natural gas</option>
						<option <?php if($car && $car['fuel']=='Hybrid - Gasoline + Electric') echo 'selected'?>>Hybrid - Gasoline + Electric</option>
						<option <?php if($car && $car['fuel']=='Hybrid - Diesel + Electric') echo 'selected'?>>Hybrid - Diesel + Electric</option>
						<option <?php if($car && $car['fuel']=='Hydrogen') echo 'selected'?>>Hydrogen</option>
						<option <?php if($car && $car['fuel']=='LPG') echo 'selected'?>>LPG</option>
						<option <?php if($car && $car['fuel']=='LPG') echo 'selected'?>>LPG</option>
					</select></td><td></td>
				</tr>
				
				<tr>
					<td>Emission standard / class<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name="emission_standard"  required>
						<option <?php if($car && $car['emission_standard']=='EURO1') echo 'selected'?>>EURO1</option>
						<option <?php if($car && $car['emission_standard']=='EURO2') echo 'selected'?>>EURO2</option>
						<option <?php if($car && $car['emission_standard']=='EURO3') echo 'selected'?>>EURO3</option>
						<option <?php if($car && $car['emission_standard']=='EURO4') echo 'selected'?>>EURO4</option>
						<option <?php if($car && $car['emission_standard']=='EURO5') echo 'selected'?>>EURO5</option>
						<option <?php if($car && $car['emission_standard']=='EURO6') echo 'selected'?>>EURO6</option>
					   </select></td><td></td>
				</tr>
				
				<tr>
					<td>Date of manufacture</td><td>
						<input type="month"  class="form-control" required name="date_manufacture"  style="width:170px!important" 
						value="<?php if ($car) {echo $car["date_manufacture"];}?>"/></td><td></td>
				</tr>
				
				<tr>
					<td>Gearbox<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name ="gearbox"  required>
						<option <?php if($car && $car['gear_box']=='Manual') echo 'selected'?>>Manual</option>
						<option <?php if($car && $car['gear_box']=='Semi-automatic') echo 'selected'?>>Semi-automatic</option>
						<option <?php if($car && $car['gear_box']=='Automatic') echo 'selected'?>>Automatic</option>
					  </select></td><td></td>
				</tr>
				
				<tr>
					<td>Drivetrain<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name ="drivetrain"  required>
						<option <?php if($car && $car['drivetrain']=='Front') echo 'selected'?>>Front</option>
						<option <?php if($car && $car['drivetrain']=='Rear') echo 'selected'?>>Rear</option>
						<option <?php if($car && $car['drivetrain']=='4x4') echo 'selected'?>>4x4</option>
					  </select></td><td></td>
				</tr>
				
				<tr>
					<td>Km<span class='req'>*</span></td><td>
						<input size="50" type="number" class="form-control" name="km"  required style="width:170px!important" value="<?php
						if ($car) {
							echo $car["cubic_capacity"];
						}
						?>"/></td><td></td>
				</tr>
				
				<tr>
					<td>VIN<span class='req'>*</span></td><td>
						<input  type="text" minlength="17" maxlength="17" class="form-control" name="vin" id="vin" required style="width:250px!important" value="<?php
						if ($car) {
							echo $car["vin"];
						}
						?>"/></td><td></td>
				</tr>
				
				<tr>
					<td>Technical status<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name ="technical_status"  required>
						<option>Accident-free</option>
						<option>Perfect status</option>
						<option>Has scratches</option>
						<option>No repairs needed</option>
						
					  </select></td><td></td>
				</tr>
				
				<tr>
					<td>Registered in Bulgaria<span class='req'>*</span></td><td>
					  <select class="form-control-sm select2" name ="registered"  required>
						<option>Yes</option>
						<option>No</option>
					  </select></td><td></td>
				</tr>
				
				<tr>
					<td>Country of origin<span class='req'>*</span></td><td>
						
					   <select class="form-control-sm select2" name ="country_of_origin" id="country_of_origin"  required>
					   <option />
					   <?php
							foreach ($countries as $country)
							{
								if($car && $car['country_of_origin'] && $car['country_of_origin']==$country['country_name'])
									echo '<option value="'.$country['country_name'].'" selected>'.$country['country_name'].'</option>';
								else
									echo '<option value="'.$country['country_name'].'">'.$country['country_name'].'</option>';
							}
					   ?>
					   </select></td><td></td>
				</tr>
				
				<tr>
					<td>Notes</td><td>
						<textarea rows="6" type="notes" class="form-control" name="notes"><?php
						if ($car) {
							echo $car["notes"];
						}
						?></textarea></td><td></td>
				</tr>
				
				<tr class="d-none">
					<td>Additionals</td><td>
						<input type="text" class="form-control" name="additionals" id="additionals" ><?php
						if ($car) {
							echo $car["additionals"];
						}
						?></textarea></td><td></td>
				</tr>
				
				
				<input class="d-none" id="btnSubmit" type="submit">
				
			</table>
			<input type="hidden" id="status" name="status" 
					value="<?php
					if ($car) {
						echo $car["status"];
					}
			?>"/>
			</form>
		</div>
	</div>
</div>


<div class="card shadow">
	<br>
	<h6 class="m-0 font-weight-bold text-primary p-4">Images</h6><span class="p-4">Maximum allowed 20 of type jpg, png, gif</span>
	<div class="collapse show" id="collapseImages">
		<div class="card-body">
			
			
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.min.css" crossorigin="anonymous">
		<link href="/fileinput/css/fileinput.css" media="all" rel="stylesheet" type="text/css"/>
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" crossorigin="anonymous">
		<link href="/fileinput/themes/explorer-fa5/theme.css" media="all" rel="stylesheet" type="text/css"/>
		<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
		<script src="/fileinput/js/plugins/buffer.min.js" type="text/javascript"></script>
		<script src="/fileinput/js/plugins/filetype.min.js" type="text/javascript"></script>
		<script src="/fileinput/js/plugins/piexif.js" type="text/javascript"></script>
		<script src="/fileinput/js/plugins/sortable.js" type="text/javascript"></script>
		<script src="/fileinput/js/fileinput.js" type="text/javascript"></script>
		<script src="/fileinput/themes/fa5/theme.js" type="text/javascript"></script>
		<script src="/fileinput/themes/explorer-fa5/theme.js" type="text/javascript"></script>
		<div class="container my-4" id="filesCtl">
    
				<!--<form action="/cars/edit/<?php echo $code;?>" method="post" accept-charset="utf-8" enctype="multipart/form-data">-->
					<div class="file-loading">
						<input id="kv-explorer" type="file" multiple>
					</div>
					<br>
					<!--
					<button type="submit" class="btn btn-primary">Submit</button>
					<button type="reset" class="btn btn-outline-secondary">Reset</button>
					-->
				<!--</form>-->
				
    
			</div>
			<script>
				
				$("#file-0").fileinput({
					theme: 'fa5',
					uploadUrl: '/cars/uploadimg/<?php echo $code;?>',
					maxFileSize: 5000,
					maxFilesNum: 20,
					allowedFileExtensions: ['jpg', 'png', 'gif']
					
				}).on('filepreupload', function(event, data, previewId, index) {
					alert('The description entered is:\n\n' + ($('#description').val() || ' NULL'));
				});
				
				
				$(".btn-warning").on('click', function () {
					var $el = $("#file-4");
					if ($el.attr('disabled')) {
						$el.fileinput('enable');
					} else {
						$el.fileinput('disable');
					}
				});
				$(".btn-info").on('click', function () {
					$("#file-4").fileinput('refresh', {previewClass: 'bg-info'});
				});
				
				$(document).ready(function () {
					
					$("#kv-explorer").fileinput({
						'theme': 'explorer-fa5',
						'uploadUrl': '/cars/uploadimg/<?php echo $code;?>',
						'allowedFileExtensions': ['jpg', 'png', 'gif'],
						'maxFileSize': 5000,
						'maxFilesNum': 10,
						overwriteInitial: false,
						initialPreviewAsData: true,
						initialPreview: [
						<?php
							if (isset($imgs)) {
								foreach ($imgs as  $img)
								{
									echo '"' .site_url().'uploads/cars_img/'.$img["url"].'",';
								}
							
							}
						?>
						],
					
						initialPreviewConfig: [
						<?php
							if (isset($imgs)) {
								foreach ($imgs as  $img)
								{
									echo '{url:"'.site_url().'cars/delimg/'.$img["id"].'"},';
								}
							
							}
						?>
						],
						
					}) ;
				   
				  
				});
			</script>
			
		</div>
	</div>
</div>


<div class="card shadow">
	<h6 class="m-0 font-weight-bold text-primary p-4">Car extra details</h6>
	<div class="collapse show" id="collapseAdditional">
		<div class="card-body">
		<?php
		
		
		require_once('form.class.php');
		//var_dump(json_decode($additionals_form,true));exit;
		if (isset($car))
			$form = new Form(['json'=>$additionals_form],$car["additionals"]);
		else
			$form = new Form(['json'=>$additionals_form],null);
		$form->show();
		?>

						
		<!--<input type="button" name="btnSave" id="btnSave" value="Save data"  class="btn btn-primary btn-sm custombtn" />-->
					   
				

		</div>
	</div>
</div>

<div class="modal fade car-preview" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="min-height:500px">
		<div class="modal-header">
        <h5 class="modal-title"><?=$code?></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      ...
	  
    </div>
  </div>
</div>

<script>
				
$('#brand1').change(function(){
	
	crtbrand=$('#brand1 ').val();

    $.ajax({
        type: "POST",
        url: "<?php echo site_url('cars/brandmodels'); ?>", 
        data:{brand: crtbrand},
        dataType:"json",//return type expected as json
        success: function(models){
			   //console.log(models)
               $.each(models,function(key,value){
				    console.log(value.model_name)
                    var opt = $('<option />'); 
                    opt.val(value.model_name);
                    opt.text(value.model_name);
                    $('#model').append(opt);
               });
			   
			   $("#model").selectpicker("refresh");
        },
    });
});


$('#btnSave').click(function(){

	saveAll(stat);
})

function saveAll(stat)
{	
	
		
	showPleaseWait()
	
	//SERIALIZE ADDITIONALS
	var additionalAll=$('#frmExtra').serializeArray();
	var additionals=[];
	for(j=0;j<additionalAll.length;j++)
	{
		addt=additionalAll[j];
		if(addt.value)
		{
			additionals.push(addt);
		}
	}
	$('#additionals').val(JSON.stringify(additionals));
	
	
	//UPLOAD IMAGES
	var node = document.querySelector('[title="Upload selected files"]');
	node.click();
	
	//var nodeFocus = document.getElementById('filesCtl');
	//nodeFocus.scrollIntoView();
	
	
	//SAVE PRIMARY
	
	if(stat==1)
	{
		$('#status').val(1);
	}
	else
		$('#status').val(0);
	
	
	setTimeout(function (){
	document.getElementById('btnSubmit').click();            
	}, 2000); 
	
	
	//document.getElementById('btnSubmit').click();
	
	//$('#frmExtra').attr('action', '/cars/additionals/<?php echo $code;?>');	
	//$("#frmExtra").submit();
}



function showPleaseWait() {    
    if (document.querySelector("#pleaseWaitDialog") == null) {
        var modalLoading = '<div class="modal" id="pleaseWaitDialog" data-backdrop="static" data-keyboard="false" role="dialog">\
            <div class="modal-dialog">\
                <div class="modal-content">\
                    <div class="modal-header">\
                        <h4 class="modal-title">Please wait...</h4>\
                    </div>\
                    <div class="modal-body">\
                        <div class="progress">\
                          <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar"\
                          aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%; height: 40px">\
                          </div>\
                        </div>\
                    </div>\
                </div>\
            </div>\
        </div>';
        $(document.body).append(modalLoading);
    }
  
    $("#pleaseWaitDialog").modal("show");
	
	function preview()
	{}
}
</script>
			

<?= $this->endsection(); ?>