<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "client_management";
$id	 			= "";
$vat 			= "";
$query_string 	= "";
$page_name      = "Add Customer";
$from 			= $_REQUEST['from'];
$tax_code 		= 2;

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){

	utility::addslashesOnAllInput(array("query_string","delivery_address_1","delivery_address_2","delivery_address_3","delivery_add_postcode","address_code","contact_title","contact_first_name","contact_surname","contact_email_address","contact_phone_no"));

	$customer_name			= $_REQUEST['customer_name'];
	$customer_code			= $_REQUEST['customer_code'];
	$invoice_address_1		= $_REQUEST['invoice_address_1'];	
	$invoice_address_2		= $_REQUEST['invoice_address_2'];	
	$invoice_address_3		= $_REQUEST['invoice_address_3'];
	$invoice_add_postcode	= $_REQUEST['invoice_add_postcode'];
	$currency				= $_REQUEST['currency'];
	$tax_code				= $_REQUEST['tax_code'];
	$default_country_code	= $_REQUEST['default_country_code'];
	$is_deliveries			= $_REQUEST['is_deliveries'];	
	$is_vac_from_works_order= $_REQUEST['is_vac_from_works_order'];
	$is_cnc_works_order		= $_REQUEST['is_cnc_works_order'];
	$is_assembly_works_order= $_REQUEST['is_assembly_works_order'];
	$created_by				= $_SESSION['user_id'];
	$created_on				= date("Y-m-d H:i:s");	
	$updated_by				= $_SESSION['user_id'];

	$sql = "customer_name = '".$customer_name."',
			customer_code = '".$customer_code."',
			invoice_address_1 = '".$invoice_address_1."',
			invoice_address_2 = '".$invoice_address_2."',
			invoice_address_3 = '".$invoice_address_3."',
			invoice_add_postcode = '".$invoice_add_postcode."',
			currency = '".$currency."',
			tax_code = '".$tax_code."',
			default_country_code = '".$default_country_code."',
			is_deliveries = '".$is_deliveries."',
			is_vac_from_works_order = '".$is_vac_from_works_order."',
			is_cnc_works_order = '".$is_cnc_works_order."',
			is_assembly_works_order = '".$is_assembly_works_order."',
			created_on = '".$created_on."',
			created_by = '".$created_by."',
			updated_by = '".$updated_by."'";

	mysqli_query($conn, "INSERT INTO $table_name SET ".$sql);
	$customer_id = mysqli_insert_id($conn);

	// Insert delivery addresses
	if(isset($_REQUEST['delivery_address_1']) && count($_REQUEST['delivery_address_1']) > 0){
		foreach($_REQUEST['delivery_address_1'] as $key => $delivery_address_1){
			$delivery_address_2		= $_REQUEST['delivery_address_2'][$key];	
			$delivery_address_3		= $_REQUEST['delivery_address_3'][$key];	
			$delivery_add_postcode	= $_REQUEST['delivery_add_postcode'][$key];
			$address_code			= $_REQUEST['address_code'][$key];
			if($delivery_address_1 != ""){				
				$sql2 = "customer_id = '".$customer_id."', address_code = '".$address_code."', delivery_address_1 = '".$delivery_address_1."', delivery_address_2 = '".$delivery_address_2."', delivery_address_3 = '".$delivery_address_3."', delivery_add_postcode = '".$delivery_add_postcode."', created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."'";
				mysqli_query($conn, "INSERT INTO client_delivery_address_mapping SET ".$sql2);
			}
		}
	}

	// Insert ALL contacts into client_contact_mapping (no main table contact fields)
	if(isset($_REQUEST['contact_first_name']) && count($_REQUEST['contact_first_name']) > 0){
		foreach($_REQUEST['contact_first_name'] as $ci => $c_fname){
			$c_title = $_REQUEST['contact_title'][$ci];
			$c_sname = $_REQUEST['contact_surname'][$ci];
			$c_email = utility::app_crypt($_REQUEST['contact_email_address'][$ci], 'e');
			$c_phone = utility::app_crypt($_REQUEST['contact_phone_no'][$ci], 'e');
			if($c_fname != ""){
				$sqlc = "INSERT INTO client_contact_mapping (customer_id, title, first_name, surname, email_address, phone_no, created_by, created_on, updated_by)
						 VALUES('$customer_id','$c_title','$c_fname','$c_sname','$c_email','$c_phone','$created_by','$created_on','$updated_by')";
				mysqli_query($conn, $sqlc);
			}
		}
	}

	// Handle file upload
	if(isset($_FILES['document_upload']['name']) && $_FILES['document_upload']['name'] != ""){
		$path = $_FILES['document_upload']['name'];
		$ext  = pathinfo($path, PATHINFO_EXTENSION);
		if(in_array(strtolower($ext), array("jpg","jpeg","png","pdf"))){
			$digits        = 5;
			$random_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
			$uploaddir     = 'customer_documents/';
			$doc_parts     = explode(".", $_FILES['document_upload']['name']);
			$docu_ext      = array_pop($doc_parts);
			$doc_name      = implode('.', $doc_parts);
			$document_upload = str_replace(" ", "_", $customer_id."_".$doc_name."_".$random_number.".".$docu_ext);
			move_uploaded_file($_FILES['document_upload']['tmp_name'], $uploaddir.$document_upload);
			mysqli_query($conn, "UPDATE $table_name SET document_upload = '$document_upload' WHERE id = '$customer_id'");
			$_SESSION['info_message'] = "File added successfully";
		} else {
			$_SESSION['message'] = "Please upload only pdf/jpg/jpeg/png";
		}
	}

	$_SESSION['info_message'] = "Customer added successfully";
	header("Location: $file_name");
	exit();
}
################################################# END INSERT #################################################


################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){

	$id          = $_REQUEST['id'];
	$customer_id = utility::app_crypt($_REQUEST['customer_id'], 'd');
	if($_REQUEST['id'] != $customer_id){
		die("Invalid URL");
	}

	$form_action  = "update";
	$button_value = "Update";
	$page_name    = "Edit Customer";
	$query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];

	$result_edit = mysqli_query($conn, "SELECT * FROM $table_name WHERE id = $id");
	$row_edit    = mysqli_fetch_array($result_edit);
	$row_edit    = utility::validate_crypt_data($row_edit);

	$customer_name			= $row_edit['customer_name'];
	$customer_code			= $row_edit['customer_code'];
	$invoice_address_1		= $row_edit['invoice_address_1'];	
	$invoice_address_2		= $row_edit['invoice_address_2'];	
	$invoice_address_3		= $row_edit['invoice_address_3'];
	$invoice_add_postcode	= $row_edit['invoice_add_postcode'];
	$currency				= $row_edit['currency'];
	$tax_code				= $row_edit['tax_code'];
	$default_country_code	= $row_edit['default_country_code'];
	$is_deliveries			= $row_edit['is_deliveries'];	
	$is_vac_from_works_order= $row_edit['is_vac_from_works_order'];
	$is_cnc_works_order		= $row_edit['is_cnc_works_order'];
	$is_assembly_works_order= $row_edit['is_assembly_works_order'];
	$document_upload		= $row_edit['document_upload'];
}
################################################# END EDIT #################################################


################################################## START UPDATE ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){

	utility::addslashesOnAllInput(array("query_string","delivery_address_1","delivery_address_2","delivery_address_3","delivery_add_postcode","delivery_address_mapping_id","address_code","contact_title","contact_first_name","contact_surname","contact_email_address","contact_phone_no","contact_mapping_id"));

	$id					 = $_REQUEST['id'];
	$customer_name		 = $_REQUEST['customer_name'];
	$customer_code		 = $_REQUEST['customer_code'];
	$invoice_address_1	 = $_REQUEST['invoice_address_1'];	
	$invoice_address_2	 = $_REQUEST['invoice_address_2'];	
	$invoice_address_3	 = $_REQUEST['invoice_address_3'];
	$invoice_add_postcode	 = $_REQUEST['invoice_add_postcode'];
	$currency				 = $_REQUEST['currency'];
	$tax_code				 = $_REQUEST['tax_code'];
	$default_country_code	 = $_REQUEST['default_country_code'];
	$is_deliveries			 = $_REQUEST['is_deliveries'];	
	$is_vac_from_works_order = $_REQUEST['is_vac_from_works_order'];
	$is_cnc_works_order		 = $_REQUEST['is_cnc_works_order'];
	$is_assembly_works_order = $_REQUEST['is_assembly_works_order'];
	$hidden_document_upload	 = $_REQUEST['hidden_document_upload'];
	$updated_by				 = $_SESSION['user_id'];
	$created_on				 = date("Y-m-d H:i:s");
	$created_by				 = $_SESSION['user_id'];

	// Handle file upload
	if(isset($_FILES['document_upload']['name']) && $_FILES['document_upload']['name'] != ""){
		$path = $_FILES['document_upload']['name'];
		$ext  = pathinfo($path, PATHINFO_EXTENSION);
		if(in_array(strtolower($ext), array("jpg","jpeg","png","pdf"))){
			$digits        = 5;
			$random_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
			$uploaddir     = 'customer_documents/';
			$old_document  = $uploaddir.$hidden_document_upload;
			if(file_exists($old_document)){ unlink($old_document); }
			$doc_parts     = explode(".", $_FILES['document_upload']['name']);
			$docu_ext      = array_pop($doc_parts);
			$doc_name      = implode('.', $doc_parts);
			$document_upload = str_replace(" ", "_", $id."_".$doc_name."_".$random_number.".".$docu_ext);
			move_uploaded_file($_FILES['document_upload']['tmp_name'], $uploaddir.$document_upload);
			$_SESSION['info_message'] = "File updated successfully";
		} else {
			$document_upload = $hidden_document_upload;
			$_SESSION['message'] = "Please upload only pdf/jpg/jpeg/png";
		}
	} else {
		$document_upload = $hidden_document_upload;
	}

	// Update main customer record (no contact_1/2/3 fields)
	$sql = "customer_name = '".$customer_name."',
			customer_code = '".$customer_code."',
			invoice_address_1 = '".$invoice_address_1."',
			invoice_address_2 = '".$invoice_address_2."',
			invoice_address_3 = '".$invoice_address_3."',
			invoice_add_postcode = '".$invoice_add_postcode."',
			currency = '".$currency."',
			tax_code = '".$tax_code."',
			default_country_code = '".$default_country_code."',
			is_deliveries = '".$is_deliveries."',
			is_vac_from_works_order = '".$is_vac_from_works_order."',
			is_cnc_works_order = '".$is_cnc_works_order."',
			is_assembly_works_order = '".$is_assembly_works_order."',
			document_upload = '".$document_upload."',
			updated_by = '".$updated_by."'";
	mysqli_query($conn, "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'");

	// Update / insert delivery addresses
	if(isset($_REQUEST['delivery_address_1']) && count($_REQUEST['delivery_address_1']) > 0){
		foreach($_REQUEST['delivery_address_1'] as $key => $delivery_address_1){
			$delivery_address_2			= $_REQUEST['delivery_address_2'][$key];	
			$delivery_address_3			= $_REQUEST['delivery_address_3'][$key];	
			$delivery_add_postcode		= $_REQUEST['delivery_add_postcode'][$key];
			$address_code				= $_REQUEST['address_code'][$key];
			$delivery_address_mapping_id= $_REQUEST['delivery_address_mapping_id'][$key];
			if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM client_delivery_address_mapping WHERE id = '$delivery_address_mapping_id'")) > 0){
				$sql1 = "UPDATE client_delivery_address_mapping SET address_code='$address_code', delivery_address_1='$delivery_address_1', delivery_address_2='$delivery_address_2', delivery_address_3='$delivery_address_3', delivery_add_postcode='$delivery_add_postcode', updated_by='$updated_by' WHERE id='$delivery_address_mapping_id'";
			} else {
				$sql1 = "INSERT INTO client_delivery_address_mapping (customer_id,address_code,delivery_address_1,delivery_address_2,delivery_address_3,delivery_add_postcode,created_by,created_on,updated_by) VALUES('$id','$address_code','$delivery_address_1','$delivery_address_2','$delivery_address_3','$delivery_add_postcode','$created_by','$created_on','$updated_by')";
			}
			mysqli_query($conn, $sql1);
		}
	}

	// Update / insert ALL contacts via client_contact_mapping only
	if(isset($_REQUEST['contact_first_name']) && count($_REQUEST['contact_first_name']) > 0){
		foreach($_REQUEST['contact_first_name'] as $ci => $c_fname){
			$c_title  = $_REQUEST['contact_title'][$ci];
			$c_sname  = $_REQUEST['contact_surname'][$ci];
			$c_email  = utility::app_crypt($_REQUEST['contact_email_address'][$ci], 'e');
			$c_phone  = utility::app_crypt($_REQUEST['contact_phone_no'][$ci], 'e');
			$c_map_id = isset($_REQUEST['contact_mapping_id'][$ci]) ? $_REQUEST['contact_mapping_id'][$ci] : '';
			if($c_fname != ""){
				if($c_map_id != "" && mysqli_num_rows(mysqli_query($conn,"SELECT * FROM client_contact_mapping WHERE id='$c_map_id'")) > 0){
					$sqlc = "UPDATE client_contact_mapping SET title='$c_title', first_name='$c_fname', surname='$c_sname', email_address='$c_email', phone_no='$c_phone', updated_by='$updated_by' WHERE id='$c_map_id'";
				} else {
					$sqlc = "INSERT INTO client_contact_mapping (customer_id,title,first_name,surname,email_address,phone_no,created_by,created_on,updated_by) VALUES('$id','$c_title','$c_fname','$c_sname','$c_email','$c_phone','$created_by','$created_on','$updated_by')";
				}
				mysqli_query($conn, $sqlc);
			}
		}
	}

	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
	$query_string = str_ireplace("page=add", "page=view", $query_string);
	$query_string = "&".$query_string;
	$customer_id  = urlencode(utility::app_crypt($id, 'e'));

	$_SESSION['info_message'] = "Customer updated successfully";
	if(isset($from) && $from == "view_client_progress"){
		header("Location: index?page=view_client_progress&from=view_customer&customer_id=$customer_id&id=$id");
		exit();
	}
	header("Location: $file_name$query_string");
	exit();
}
################################################# END UPDATE #################################################
?>
<style>
em { color: red; font-size: 20px; position: absolute; }
fieldset {
	border-top: 4px solid #dedede;
	border-right: 1px solid #dedede;
	border-bottom: 1px solid #dedede;
	border-left: 1px solid #dedede;
	padding: 15px;
	margin-bottom: 10px;
}
legend { width: auto; color: #a423a4; }
</style>

<!---------------------------------- Cloning template: Delivery Address --------------------------------------------->
<div class="col-sm-12 col-lg-12 col-12" id="delivery_address_div_to_clone" style="display:none;">
	<div class="row">
		<div class="col-sm-2">
			<label class="control-label">&nbsp;</label>
			<input type="text" class="form-control" name="address_code[]" value="" placeholder="Address Code" autocomplete="off">
		</div>
		<div class="col-sm-2">
			<label class="control-label">&nbsp;</label>
			<input type="text" class="form-control" name="delivery_address_1[]" value="" placeholder="Address 1" autocomplete="off" required>
		</div>
		<div class="col-sm-2">
			<label class="control-label">&nbsp;</label>
			<input type="text" class="form-control" name="delivery_address_2[]" value="" placeholder="Address 2" autocomplete="off" required>
		</div>
		<div class="col-sm-2">
			<label class="control-label">&nbsp;</label>
			<input type="text" class="form-control" name="delivery_address_3[]" value="" placeholder="Address 3" autocomplete="off" required>
		</div>
		<div class="col-sm-2">
			<label class="control-label">&nbsp;</label>
			<input type="text" class="form-control" name="delivery_add_postcode[]" value="" placeholder="Postcode" autocomplete="off">
		</div>
		<div class="col-sm-1" style="margin-top:35px;">
			<span class="fa fa-trash delete_new_delivery_addres" alt="" style="color:red;cursor:pointer;"></span>
		</div>
	</div>
</div>

<!---------------------------------- Cloning template: Contact Row --------------------------------------------->
<div class="col-sm-12 col-lg-12 col-12" id="contact_row_div_to_clone" style="display:none;">
	<div class="row align-items-end mb-2">
		<div class="col-lg-1">
			<label class="control-label">Title</label>
			<?php echo Keycode::getKeycodeListValue("contact_title[]", "", "100%", "Please Select", "id", "code", "title", "", "form-control", false, ""); ?>
		</div>
		<div class="col-lg-2">
			<label class="control-label">First Name</label>
			<input type="text" class="form-control" name="contact_first_name[]" value="" placeholder="First Name" autocomplete="off">
		</div>
		<div class="col-lg-2">
			<label class="control-label">Surname</label>
			<input type="text" class="form-control" name="contact_surname[]" value="" placeholder="Surname" autocomplete="off">
		</div>
		<div class="col-lg-3">
			<label class="control-label">Email address</label>
			<input type="email" class="form-control contact_email_field" name="contact_email_address[]" value="" placeholder="Email address" autocomplete="off">
			<span class="invalid-feedback contact_email_error" style="display:none;">Invalid email format. Must contain '@'</span>
		</div>
		<div class="col-lg-2">
			<label class="control-label">Phone No.</label>
			<input type="text" class="form-control" name="contact_phone_no[]" value="" placeholder="Phone No." pattern="^\+?[0-9\s()-]*$" oninput="this.value = this.value.replace(/[^0-9+\s()-]/g, '')" autocomplete="off">
		</div>
		<input type="hidden" name="contact_mapping_id[]" value="">
		<div class="col-lg-1" style="margin-bottom:5px;">
			<span class="fa fa-trash delete_contact_row" data-map_id="" style="color:red;cursor:pointer;font-size:18px;" title="Remove Contact"></span>
			<i class="fas fa-sync-alt fa-spin contact_row_loader" style="font-size:18px;display:none;"></i>
			<i class="fa fa-check contact_row_done" style="color:#bad23a;font-size:18px;display:none;"></i>
		</div>
	</div>
</div>
<!----------------------------------- End cloning templates --------------------------------------------->

<section class="content-header">
	<div class="container-fluid">
		<div class="row mb-2">
			<div class="col-sm-6">
				<h1><?=$page_name;?></h1>
			</div>
			<div class="col-sm-6">
				<?php
				$query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
				if(isset($from) && $from == "view_client_progress"){
					$query_string = str_ireplace("page=add", "page=view_client_progress", $query_string);
				} else {
					$query_string = str_ireplace("page=add", "page=view", $query_string);
				}
				?>
				<button type="button" style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-primary" onclick="window.location.href='index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>

<section class="content">
	<div class="row">
		<div class="col-12">

			<?php if(isset($_SESSION['info_message'])){ ?>
			<div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<?php echo $_SESSION['info_message']; unset($_SESSION['info_message']); ?>
			</div>
			<?php } ?>

			<div class="card">
				<form method="post" name="form1" id="form1" action="index?page=add&action=<?php echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
					<div class="card-body">
						<div class="row">
							<div class="col-lg-12 col-sm-12">

								<!-- ===== DETAILS ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Details</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<div class="row">
										<div class="col-lg-6">
											<label class="control-label">Customer Name<em>*</em></label>
											<input type="text" id="customer_name" name="customer_name" value="<?php echo $customer_name;?>" class="form-control" placeholder="Customer Name" required>
										</div>
										<div class="col-lg-6">
											<label class="control-label">Customer Code<em>*</em></label>
											<input type="text" id="customer_code" name="customer_code" value="<?php echo $customer_code;?>" class="form-control" placeholder="Customer Code" required>
										</div>
									</div>
								</div>

								<!-- ===== DELIVERY ADDRESS ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Delivery Address</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<?php
									$delivery_address_sql    = mysqli_query($conn, "SELECT * FROM client_delivery_address_mapping WHERE customer_id='".$id."'");
									$delivery_address_result = mysqli_num_rows($delivery_address_sql);
									if($delivery_address_result > 0){
										$j = 0;
										while($mapp_row = mysqli_fetch_array($delivery_address_sql)){
									?>
									<div class="col-sm-12 col-lg-12 col-12 initial_row_for_delivery_addres" id="new_delivery_addres<?=$mapp_row['id'];?>" data-personal_count="<?=$mapp_row['id'];?>">
										<div class="row">
											<div class="col-sm-2">
												<label class="control-label">Address Code</label>
												<input type="text" name="address_code[<?=$j;?>]" class="form-control" value="<?php echo $mapp_row['address_code'];?>" placeholder="Address Code">
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 1<em>*</em></label>
												<input type="text" name="delivery_address_1[<?=$j;?>]" class="form-control" value="<?php echo $mapp_row['delivery_address_1'];?>" placeholder="Address 1" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 2<em>*</em></label>
												<input type="text" name="delivery_address_2[<?=$j;?>]" class="form-control" value="<?php echo $mapp_row['delivery_address_2'];?>" placeholder="Address 2" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 3<em>*</em></label>
												<input type="text" name="delivery_address_3[<?=$j;?>]" class="form-control" value="<?php echo $mapp_row['delivery_address_3'];?>" placeholder="Address 3" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Postcode</label>
												<input type="text" name="delivery_add_postcode[<?=$j;?>]" class="form-control" value="<?php echo $mapp_row['delivery_add_postcode'];?>" placeholder="Postcode">
											</div>
											<div class="col-sm-1" style="margin-top:35px;">
												<input type="hidden" name="delivery_address_mapping_id[<?=$j;?>]" value="<?php echo $mapp_row['id'];?>">
												<?php if($j != 0){ ?>
												<span class="fa fa-trash delete_new_delivery_addres" style="cursor:pointer;color:red;" alt="<?php echo $mapp_row['id'];?>"></span>
												<?php } ?>
												<i class="fas fa-sync-alt fa-spin" id="load_new_delivery_addres_<?=$mapp_row['id'];?>" style="font-size:20px;display:none;"></i>
												<i class="fa fa-check" id="status_update_personal_done_<?=$mapp_row['id'];?>" style="color:#bad23a;font-size:20px;display:none;"></i>
											</div>
										</div>
									</div>
									<?php $j++; }
									} else { ?>
									<div class="col-sm-12 col-lg-12 col-12 initial_row_for_delivery_addres" id="new_delivery_addres0" data-personal_count="0">
										<div class="row">
											<div class="col-sm-2">
												<label class="control-label">Address Code</label>
												<input type="text" class="form-control" name="address_code[]" value="" placeholder="Address Code" autocomplete="off">
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 1<em>*</em></label>
												<input type="text" class="form-control" name="delivery_address_1[]" value="" placeholder="Address 1" autocomplete="off" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 2<em>*</em></label>
												<input type="text" class="form-control" name="delivery_address_2[]" value="" placeholder="Address 2" autocomplete="off" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Address 3<em>*</em></label>
												<input type="text" class="form-control" name="delivery_address_3[]" value="" placeholder="Address 3" autocomplete="off" required>
											</div>
											<div class="col-sm-2">
												<label class="control-label">Postcode</label>
												<input type="text" class="form-control" name="delivery_add_postcode[]" value="" placeholder="Postcode" autocomplete="off">
											</div>
										</div>
									</div>
									<?php } ?>
									<div class="col-sm-12 delivery_address_div_to_append">
										<label class="add_one_more_delivery_addres" style="cursor:pointer;color:#a423a4;"><span class="fa fa-plus"></span> Add More</label>
									</div>
								</div>

								<!-- ===== INVOICE ADDRESS ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Invoice Address</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<?php if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){ $hide = "hide"; } ?>
									<div class="form-group <?php echo $hide; ?>" style="display:flex;align-items:center;gap:10px;">
										<label class="control-label" style="margin:0;">Same as Delivery Address 1</label>
										<input type="checkbox" class="flat-red" id="is_same_as_delivery_add" name="is_same_as_delivery_add" value="1" <?php echo ($is_same_as_delivery_add == 1) ? 'checked' : ''; ?>>
									</div>
									<div class="row">
										<div class="col-lg-3">
											<label class="control-label">Invoice Address 1<em>*</em></label>
											<input type="text" id="invoice_address_1" name="invoice_address_1" value="<?php echo $invoice_address_1;?>" class="form-control" placeholder="Invoice Address 1" required>
										</div>
										<div class="col-lg-3">
											<label class="control-label">Invoice Address 2<em>*</em></label>
											<input type="text" id="invoice_address_2" name="invoice_address_2" value="<?php echo $invoice_address_2;?>" class="form-control" placeholder="Invoice Address 2" required>
										</div>
										<div class="col-lg-3">
											<label class="control-label">Invoice Address 3<em>*</em></label>
											<input type="text" id="invoice_address_3" name="invoice_address_3" value="<?php echo $invoice_address_3;?>" class="form-control" placeholder="Invoice Address 3" required>
										</div>
										<div class="col-lg-3">
											<label class="control-label">Postcode</label>
											<input type="text" id="invoice_add_postcode" name="invoice_add_postcode" value="<?php echo $invoice_add_postcode;?>" class="form-control" placeholder="Postcode">
										</div>
									</div>
								</div>

								<!-- ===== CONTACTS — fully dynamic, all from client_contact_mapping ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Contacts</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">

									<div id="contacts_wrapper">
										<?php
										// Load all contacts from mapping table
										$contacts_to_render = array();
										if(!empty($id)){
											$contacts_sql = mysqli_query($conn, "SELECT * FROM client_contact_mapping WHERE customer_id='".$id."' ORDER BY id ASC");
											if($contacts_sql && mysqli_num_rows($contacts_sql) > 0){
												while($crow = mysqli_fetch_array($contacts_sql)){
													$crow = utility::validate_crypt_data($crow);
													$contacts_to_render[] = array(
														'title'      => $crow['title'],
														'first_name' => $crow['first_name'],
														'surname'    => $crow['surname'],
														'email'      => $crow['email_address'],
														'phone'      => $crow['phone_no'],
														'map_id'     => $crow['id'],
													);
												}
											}
										}
										// Always show at least one blank row
										if(empty($contacts_to_render)){
											$contacts_to_render[] = array('title'=>'','first_name'=>'','surname'=>'','email'=>'','phone'=>'','map_id'=>'');
										}

										foreach($contacts_to_render as $ci => $c):
											$is_first = ($ci === 0);
										?>
										<div class="col-sm-12 col-lg-12 col-12 contact_row_item" id="contact_row_<?=$ci;?>" data-contact_index="<?=$ci;?>">
											<div class="row align-items-end mb-2">
												<div class="col-lg-1">
													<label class="control-label">Title</label>
													<?php echo Keycode::getKeycodeListValue("contact_title[]", $c['title'], "100%", "Please Select", "id", "code", "title", "", "form-control", false, ""); ?>
												</div>
												<div class="col-lg-2">
													<label class="control-label">First Name</label>
													<input type="text" name="contact_first_name[]" value="<?php echo $c['first_name'];?>" class="form-control" placeholder="First Name">
												</div>
												<div class="col-lg-2">
													<label class="control-label">Surname</label>
													<input type="text" name="contact_surname[]" value="<?php echo $c['surname'];?>" class="form-control" placeholder="Surname">
												</div>
												<div class="col-lg-3">
													<label class="control-label">Email address</label>
													<input type="email" name="contact_email_address[]" value="<?php echo $c['email'];?>" class="form-control contact_email_field" placeholder="Email address">
													<span class="invalid-feedback contact_email_error" style="display:none;">Invalid email format. Must contain '@'</span>
												</div>
												<div class="col-lg-2">
													<label class="control-label">Phone No.</label>
													<input type="text" name="contact_phone_no[]" value="<?php echo $c['phone'];?>" class="form-control" placeholder="Phone No." pattern="^\+?[0-9\s()-]*$" oninput="this.value = this.value.replace(/[^0-9+\s()-]/g, '')">
												</div>
												<input type="hidden" name="contact_mapping_id[]" value="<?php echo $c['map_id'];?>">
												<?php if(!$is_first): ?>
												<div class="col-lg-1" style="margin-bottom:5px;">
													<span class="fa fa-trash delete_contact_row" data-map_id="<?php echo $c['map_id'];?>" style="color:red;cursor:pointer;font-size:18px;" title="Remove Contact"></span>
													<i class="fas fa-sync-alt fa-spin contact_row_loader" style="font-size:18px;display:none;"></i>
													<i class="fa fa-check contact_row_done" style="color:#bad23a;font-size:18px;display:none;"></i>
												</div>
												<?php endif; ?>
											</div>
										</div>
										<?php endforeach; ?>
									</div><!-- /#contacts_wrapper -->

									<div class="col-sm-12 contact_div_to_append">
										<label class="add_one_more_contact" style="cursor:pointer;color:#a423a4;">
											<span class="fa fa-plus"></span> Add More Contact
										</label>
									</div>
								</div>

								<!-- ===== FINANCE ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Finance</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<div class="row">
										<div class="col-lg-4">
											<label class="control-label">Currency<em>*</em></label>
											<?php $gsi->getCurrencyList("currency", $currency, "100%", false, "form-control select2", "required"); ?>
										</div>
										<div class="col-lg-4">
											<label class="control-label">Tax Code<em>*</em></label>
											<?php $gsi->getTaxCodeList("tax_code", $tax_code, "100%", false, "form-control", "required"); ?>
										</div>
										<div class="col-lg-4">
											<label class="control-label">Default Country Code<em>*</em></label>
											<?php $gsi->getCountryCodeList("default_country_code", $default_country_code, "100%", false, "form-control select2", "required"); ?>
										</div>
									</div>
								</div>

								<!-- ===== ON HOLD FOR ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">On Hold for</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<div class="row">
										<div class="col-lg-3">
											<label class="control-label">Deliveries</label>
											<div><input type="checkbox" class="flat-red" id="is_deliveries" name="is_deliveries" value="1" <?php echo ($is_deliveries == 1) ? 'checked' : ''; ?>></div>
										</div>
										<div class="col-lg-3">
											<label class="control-label">VAC from works order</label>
											<div><input type="checkbox" class="flat-red" id="is_vac_from_works_order" name="is_vac_from_works_order" value="1" <?php echo ($is_vac_from_works_order == 1) ? 'checked' : ''; ?>></div>
										</div>
										<div class="col-lg-3">
											<label class="control-label">CNC works order</label>
											<div><input type="checkbox" class="flat-red" id="is_cnc_works_order" name="is_cnc_works_order" value="1" <?php echo ($is_cnc_works_order == 1) ? 'checked' : ''; ?>></div>
										</div>
										<div class="col-lg-3">
											<label class="control-label">Assembly works order</label>
											<div><input type="checkbox" class="flat-red" id="is_assembly_works_order" name="is_assembly_works_order" value="1" <?php echo ($is_assembly_works_order == 1) ? 'checked' : ''; ?>></div>
										</div>
									</div>
								</div>

								<!-- ===== FILES ===== -->
								<div class="form-section mt-2">
									<h4 style="margin-top:0;margin-bottom:0;color:#9c4893;">Files</h4>
									<hr style="background-color:#9c4893;height:1px;margin-top:0;margin-bottom:1;">
									<div class="form-group">
										<label class="control-label">File</label><br/>
										<span style="font-weight:bold;color:#ff0000;">(Please upload only pdf/jpg/jpeg/png)</span><br/>
										<input type="file" name="document_upload" id="document_upload" accept=".pdf,.jpg,.jpeg,.png"/>
										<div>
										<?php
										$dir = "customer_documents/";
										if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
											if(is_file($dir.$document_upload)){
												$ext = pathinfo($document_upload, PATHINFO_EXTENSION);
												if(in_array($ext, array("jpg","jpeg","png"))){
													echo '<a href="../'.$dir.$document_upload.'" target="_blank"><img style="width:100px;border:1px solid #777" src="../'.$dir.$document_upload.'"></a>';
												} elseif($ext == "pdf"){
													echo '<a href="../'.$dir.$document_upload.'" target="_blank"><span class="text-primary" title="'.$document_upload.'">'.utility::ellipsis($document_upload, 20).'</span></a>';
												}
											} else {
												echo '<img style="width:100px;border:1px solid #777" src="../'.$dir.'no-image.gif">';
											}
										}
										?>
										<input type="hidden" name="hidden_document_upload" value="<?php echo $document_upload;?>">
										</div>
									</div>
								</div>

							</div>
						</div><!-- /.row -->
					</div><!-- /.card-body -->

					<div class="card-footer">
						<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
						<input type="hidden" id="from" name="from" value="<?php echo $from;?>">
						<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
						<button type="submit" id="submit" name="submit" value="<?php echo $button_value;?>" class="btn btn-primary">
							Submit <i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
						</button>
					</div>
				</form>
			</div><!-- /.card -->
		</div>
	</div>
</section>

<script type="text/javascript">
$(function(){

	// Disable submit on submit to prevent double-click
	$('#form1').submit(function(){
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});

	// ===== EMAIL VALIDATION (delegated — works for dynamic rows too) =====
	$(document).on('blur', '.contact_email_field', function(){
		var email = $(this).val();
		var errorSpan = $(this).siblings('.contact_email_error');
		if(email === '' || email.includes('@')){
			errorSpan.hide();
		} else {
			errorSpan.show();
		}
	});

	// ===== DELIVERY ADDRESS: ADD MORE =====
	$('.add_one_more_delivery_addres').click(function(){
		$('#delivery_address_div_to_clone').show();
		var div_count = parseInt($('.initial_row_for_delivery_addres').last().attr("data-personal_count")) + 1;
		var cloned_div = $('#delivery_address_div_to_clone').clone()
			.addClass("initial_row_for_delivery_addres")
			.attr("id", "new_delivery_addres" + div_count)
			.attr("data-personal_count", div_count);
		$('.delivery_address_div_to_append').before(cloned_div);
		$('#delivery_address_div_to_clone').hide();
	});

	// ===== DELIVERY ADDRESS: DELETE =====
	$("#form1").on("click", ".delete_new_delivery_addres", function(){
		if(confirm('Are you sure you want to delete?')){
			var map_id = $(this).attr("alt");
			if(map_id && map_id != ""){
				$('#load_new_delivery_addres_' + map_id).show();
				$.ajax({
					type: "POST",
					url: site_url + "/client_management/index?page=ajax_actions&action=delete_delivery_address_mapping",
					data: {delivery_address_mapping_id: map_id},
					success: function(result){
						var res = jQuery.parseJSON(result);
						if(res.status == "success"){
							$('#load_new_delivery_addres_' + map_id).hide();
							$('#status_update_personal_done_' + map_id).show();
							setTimeout(function(){
								$('#status_update_personal_done_' + map_id).hide();
								$('#new_delivery_addres' + map_id).remove();
							}, 1000);
						}
					}
				});
			} else {
				$(this).closest('.initial_row_for_delivery_addres').remove();
			}
		}
	});

	// ===== SAME AS DELIVERY ADDRESS CHECKBOX =====
	$('#is_same_as_delivery_add').on('change', function(){
		var isChecked = $(this).is(':checked');
		var deliveryDiv = $('#new_delivery_addres0');
		if(isChecked){
			$('#invoice_address_1').val(deliveryDiv.find('input[name="delivery_address_1[]"]').val());
			$('#invoice_address_2').val(deliveryDiv.find('input[name="delivery_address_2[]"]').val());
			$('#invoice_address_3').val(deliveryDiv.find('input[name="delivery_address_3[]"]').val());
			$('#invoice_add_postcode').val(deliveryDiv.find('input[name="delivery_add_postcode[]"]').val());
		} else {
			$('#invoice_address_1, #invoice_address_2, #invoice_address_3, #invoice_add_postcode').val('');
		}
	});

	// ===== CONTACTS: ADD MORE =====
	$('.add_one_more_contact').click(function(){
		var contact_count = $('.contact_row_item').length;
		// Clone from hidden template
		var cloned = $('#contact_row_div_to_clone').clone()
			.addClass("contact_row_item")
			.attr("id", "contact_row_" + contact_count)
			.attr("data-contact_index", contact_count)
			.css("display", ""); // make visible (override display:none from template)
		// Clear all values
		cloned.find('input[type="text"], input[type="email"]').val('');
		cloned.find('select').val('');
		cloned.find('input[type="hidden"]').val('');
		$('.contact_div_to_append').before(cloned);
	});

	// ===== CONTACTS: DELETE =====
	$("#form1").on("click", ".delete_contact_row", function(){
		if(confirm('Are you sure you want to remove this contact?')){
			var map_id = $(this).data("map_id");
			var row    = $(this).closest('.contact_row_item');
			var loader = $(this).siblings('.contact_row_loader');
			var done   = $(this).siblings('.contact_row_done');
			if(map_id && map_id != ""){
				// Saved record — delete via AJAX
				loader.show();
				$.ajax({
					type: "POST",
					url: site_url + "/client_management/index?page=ajax_actions&action=delete_contact_mapping",
					data: {contact_mapping_id: map_id},
					success: function(result){
						var res = jQuery.parseJSON(result);
						if(res.status == "success"){
							loader.hide();
							done.show();
							setTimeout(function(){
								done.hide();
								row.remove();
							}, 1000);
						} else {
							loader.hide();
							alert('Could not delete contact. Please try again.');
						}
					},
					error: function(){
						loader.hide();
						alert('An error occurred. Please try again.');
					}
				});
			} else {
				// Unsaved (new) row — just remove from DOM
				row.remove();
			}
		}
	});

});
</script>