
<?= $this->extend('layouts/main.php') ?>

<?= $this->section('content') ?>
<?php
// dd($reff);
$dests = array();
$origins = array();
foreach($invcounters as $qdata) {
	$qid = "C|".$qdata['counterid'];
	$qname = "Counter - (".$qdata['counternumber'].") ".$qdata['countername'];
	$dests[$qid]=$qname;
	$origins[$qid]=$qname;
}
foreach($vendors as $qdata) {
	$qid = "V|".$qdata['vendorid'];
	$qname = "Vendor - (".$qdata['initial'].") ".$qdata['vendorname'];
	$origins[$qid]=$qname;
}
foreach($products as $qdata) {
	$qid = "P|".$qdata['productid'];
	$qname = $qdata['sitename']." - ".$qdata['productname']." (".$qdata['productnumber'].")";
	$dests[$qid]=$qname;
	$origins[$qid]=$qname;
}

$now = date('Y-m-d\TH:i');
$siteid = '';
$productid = '';
$vendorid = '';
$swversion = '';
$acttypeid = '';
$userid_owner = '';
$activitystatus = 'O';
$actid_ref = $actid_ref ?? 0; // Ini untuk edit dan create biasa
$reportfrom = '';
$reportdate = $now;
$opendate = $now;
$closedate = '';
$media = '';
$action = '';
$subject = '';
$actdetailid = '';
$acttextid = '';
$textvalue = array();
$attachment = '';
$actby = '';
$disable = '';
if(isset($activities)) { $data = $activities[0]; }
if(isset($new_value)) { $data = $new_value; }
if(isset($data)) {
	// dd($data);
	if(isset($data['actid'])) { $productid = $data['productid']; }
	$siteid = $data['siteid'];
	$productid = $data['productid'];
	$vendorid = $data['vendorid'];
	$swversion = $data['swversion'];
	$acttypeid = $data['acttypeid'];
	$userid_owner = $data['userid_owner'];
	$activitystatus = $data['activitystatus'];

	// Untuk REFF : Menentukan mana yg dipakai untuk actid_ref
	if ($refer_page) {
		$actid_ref = $data['actid']; // controller refercreate dijalankan
	} else {
		$actid_ref = $data['actid_ref']; // controller edit dijalankan
	}
	
	$actby = $data['actby'];
	$reportfrom = $data['reportfrom'];
	$reportdate = $data['reportdate'];
	$opendate = $data['opendate'];
	$closedate = $data['closedate'];
	$media = $data['media'];
	$action = $data['action'];
	$subject = $data['subject'];
	$attachment = $data['attachment'];
	if(isset($data['actdetailid'])) {
		$actdetailid = $data['actdetailid'];
		$acttextid = $data['acttextid'];
		$textvalue = $data['textvalue'];
	}
}
?>
<?php //dd($activitystatus);?>
<div class="page-wrapper">
	<div class="container-fluid">
		<div class="row page-titles">
			<div class="col-md-5 align-self-center">
				<h4 class="text-themecolor">New Activity</h4>
			</div>
		</div>
		<?php if(isset($validation)) {	?>
		<div class="row">
			<div class="col-12">
				<div class='alert alert-danger alert-dismissible'>
					<?= $validation->listErrors(); ?>
					<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> <span aria-hidden="true"></span> </button>
				</div>
			</div>
		</div>
		<?php }	?>
		<div class="row">
			<div class="col-12">
				<form method="post" enctype="multipart/form-data">

					<input type='hidden' name='userid_creator' value='<?=$_SESSION['userid'];?>' /> 
					
					<div class="card">
						<div class="card-body">
							<div class="row">
								<div class="accordion accordion-flush mb-3" id="accordionExample">
									<!-- Site / Product -->
									<div class="accordion-item">
										<h2 class="accordion-header" id="headingTwo">
										<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
											<span class="me-3"> Site & Product </span>
											<!-- <span id="sitespan" class="d-block text-danger"> <i class="fas fa-exclamation-triangle fa-bounce fs-4"></i> </span> -->
										</button>
										</h2>
										<div id="collapseTwo" class="accordion-collapse collapse show bg-white" aria-labelledby="headingTwo">
											<div class="accordion-body ps-0">	
												<div class="row">
													<div class='form-group col-12 col-lg-6'>
														<label for="site" class="form-label border-start border-5 border-primary ps-1">Site</label>
														<select name="siteid" id="siteid" class="form-select form-select-sm select2 site" required>
															<option value="">-- Choose one --</option>
															<?php 
															foreach ($sites as $data) {
																$qsiteid = $data['siteid'];
																$qsitename = $data['sitename'];
																if($qsiteid == $siteid) { echo "<option value='$qsiteid' selected>$qsitename</option>"; }
																else { echo "<option value='$qsiteid'>$qsitename</option>"; }
															}
															?>
														</select>
													</div>
													<div class='form-group col-12 col-lg-6'>
														<label for="actby" class="form-label border-start border-5 border-primary ps-1">Activity by</label>
														<select name="actby" id="actby" class="form-select form-select-sm">
															<option value="">-- Choose one --</option>
															<?php 
															foreach ($actbys as $qid => $qvalue) {
																if($qid == $actby) { echo "<option value='$qid' selected>$qvalue</option>"; }
																else { echo "<option value='$qid'>$qvalue</option>"; }
															}
															?>
														</select>
													</div>
												</div>
												<div class='row'>
													<span id='actby_item'>
													<?php 
														if($actby == 'P') { echo $controller->getproduct($siteid, $productid, $swversion); } 
														elseif ($actby == 'V') { echo $controller->getvendor($vendorid); }
														elseif ($actby == 'C') { echo $controller->getconsumable($actid); }
													?>
													</span>
												</div>												
											</div>
										</div>									
									</div>
									
									<!-- AR info -->
									<div class="accordion-item">
										<h2 class="accordion-header" id="headingOne">
										<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
											<span class="me-3"> Activity Info </span>
											<!-- <span id="activityspan" class="d-block text-danger"> <i class="fas fa-exclamation-triangle fa-bounce fs-4"></i> </span> -->
										</button>
										</h2>
										<div id="collapseOne" class="accordion-collapse collapse show bg-white" aria-labelledby="headingOne">
											<div class="accordion-body ps-0">
												<div class="row mb-2">
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="acttypeid" class="form-label border-start border-5 border-primary ps-1">Activity Type</label>
															<select name="acttypeid" id="acttypeid" class="form-select form-select-sm select2" required>
																<option value="" selected disabled>-- Choose one --</option>
																<?php foreach($acttype as $data) {
																	$qacttypeid = $data['acttypeid'];
																	$qacttypecode = $data['acttypecode'];
																	$qfulltext = $data['fulltext'];
																	if($acttypeid == $qacttypeid) { echo "<option value='$qacttypeid' selected>$qacttypecode - $qfulltext</option>"; }
																	else { echo "<option value='$qacttypeid'>$qacttypecode - $qfulltext</option>"; }
																} ?>
															</select>
														</div>
													</div>
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="owner" class="form-label border-start border-5 border-primary ps-1">Activity Owner</label>
															<select name="userid_owner" class="form-select form-select-sm select2">
																<option value="">-- Choose one --</option>
																<?php 
																	foreach ($users as $data) {
																		$quserid = $data['userid'];
																		$qfirstname = $data['firstname'];
																		$qlastname = $data['lastname'];
																		if( $userid_owner=='' ) { $userid_owner = $_SESSION['userid']; }
																		if( $quserid== $userid_owner ) { echo "<option value='$quserid' selected>$qfirstname $qlastname</option>"; }
																		else { echo "<option value='$quserid'>$qfirstname $qlastname</option>"; }
																	} 
																?>
															</select>
														</div>
													</div>
												</div>
												<div class="row mb-2">
													<div class="col-6">
														<div class="form-group">
															<label class="form-label border-start border-5 border-primary ps-1">Certificate</label>
															<div class="row">
																<div class="col-md-6 mb-2">
																	<div class="form-check">
																		<input class="form-check-input" type="checkbox" name="calibration" id="calibration" value="1">
																		<label class="form-check-label" for="calibration">
																			Calibration
																		</label>
																	</div>
																</div>
																<div class="col-md-6 mb-2">
																	<div class="form-check">
																		<input class="form-check-input" type="checkbox" name="installation" id="installation" value="1">
																		<label class="form-check-label" for="installation">
																			Installation Certificate
																		</label>
																	</div>
																</div>
																<div class="col-md-6 mb-2">
																	<div class="form-check">
																		<input class="form-check-input" type="checkbox" name="maintenance" value="1" id="maintenance" >
																		<label class="form-check-label" for="maintenance">
																			Maintenance Certificate
																		</label>
																	</div>
																</div>
																<div class="col-md-6 mb-2">
																	<div class="form-check">
																		<input class="form-check-input" type="checkbox" name="offreport" value="1" id="offreport" >
																		<label class="form-check-label" for="offreport">
																			Berita Acara Instalasi
																		</label>
																	</div>
																</div>
																<div class="col-md-6 mb-2">
																	<div class="form-check">
																		<input class="form-check-input" type="checkbox" name="training" value="1" id="training" >
																		<label class="form-check-label" for="training">
																			User Training Certificate
																		</label>
																	</div>
																</div>
															</div>
														</div>
													</div>
												</div>
												<div class="row mb-2">
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="status" class="form-label border-start border-5 border-primary ps-1">Activity Status</label>
															<select name="activitystatus" id="status" class="form-select form-select-sm" onchange='changestatus()' required>
																<option value="" disabled>-- Choose one --</option>
																<?php
																	foreach ($stats as $statcode => $stat) {
																		// if( $statcode == 'S' OR $statcode == 'D') {continue;}
																		if( $statcode == $activitystatus ) { echo "<option value='$statcode' selected>$stat</option>"; }
																		else { echo "<option value='$statcode'>$stat</option>"; }
																	}
																?>
															</select>
														</div>
													</div>
													<div class="col-12 col-md-6">
														<div class="form-group">
															<!-- <label for="actid_ref" class="form-label border-start border-5 border-primary ps-1">Referred incident ID</label>
															<input type="hidden" name="actid_reff" value">
															<input type="text" class="form-control form-control-sm" disabled name="actid_reff" id="actid_reff" value="<?php //echo '(ACTID-' . $reff['actid'] . ') (' . $reff['fullname'] . ') (' . $reff['sitename'] . ') ' . $reff['subject']; ?>"> -->
															<label for="actid_ref" class="form-label border-start border-5 border-primary ps-1">Referred incident ID</label>
															<select name="actid_ref" id="actid_ref" class="form-select form-select-sm select2 actid_ref" <?= $actid_ref_status;?>>
																<!-- <option value="">-- Choose one --</option> -->
																<?php
																foreach ($reff as $data) {
																	$qreffactid = $data['actid'];
																	$qsubject = $data['subject'];
																	$qfullname = $data['fullname'];
																	$qsitename = $data['sitename'];
																	if($qreffactid == $actid_ref) { echo "<option value='$qreffactid' selected>($qreffactid - $qfullname) $qsitename - $qsubject</option>"; }
																	else { echo "<option value='$qreffactid'>($qreffactid - $qfullname) $qsitename - $qsubject</option>"; }
																}
																?>
															</select>
														</div>
													</div>
												</div>
												
												<div class="row mb-2">
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="reportdate" class="form-label border-start border-5 border-primary ps-1">Report date</label>
															<input type="text" class="form-control form-control-sm" name="reportdate" id="reportdate" value='<?=$reportdate;?>'>
														</div>
													</div>
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="report" class="form-label border-start border-5 border-primary ps-1">Report from</label>
															<input type='text' class='form-control form-control-sm' name='reportfrom' value='<?=$reportfrom;?>' />
															<!--
															<select name="report" id="report" class="form-select form-select-sm select2">
																<option value="" selected>-- Choose one --</option>
																<?php 
																	/*
																	foreach ($contacts as $data) {
																		echo "<option value="<?=$data['contactid'];?>"><?=$data['firstname'];?></option>";
																	} 
																	*/
																?>
															</select>
															-->
														</div>
													</div>
												</div>
												<div class="row mb-2">
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="open" class="form-label border-start border-5 border-primary ps-1">Open date</label>
															<input type="text" class="form-control form-control-sm" name="opendate" id="opendate" value='<?=$opendate;?>'>
														</div>
													</div>
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="close" class="form-label border-start border-5 border-primary ps-1">Close date</label>
															<input type="text" class="form-control form-control-sm closedate" name="closedate" autocomplete="off" value='<?=$closedate;?>' <?php if($activitystatus=='O') echo "disabled";?> required>
														</div>
													</div>
												</div>
												<div class="row">
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="media" class="form-label border-start border-5 border-primary ps-1">Media</label>
															<select name="media" id="media" class="form-select form-select-sm" >
																<option value="" selected >-- Choose one --</option>
																<?php
																foreach($medias as $qid => $qtext) {
																	if($qid == $media) { echo "<option value='$qid' selected>$qtext</option>"; }
																	else { echo "<option value='$qid'>$qtext</option>"; }
																}
																?>
															</select>
															
														</div>
													</div>
													<div class="col-12 col-md-6">
														<div class="form-group">
															<label for="actionby" class="form-label border-start border-5 border-primary ps-1">Action</label>
															<select name="action" id="action" class="form-select form-select-sm" >
																<option value="" selected >-- Choose one --</option>
																<?php
																foreach($actions as $qid => $qtext) {
																	if($qid == $action) { echo "<option value='$qid' selected>$qtext</option>"; }
																	else { echo "<option value='$qid'>$qtext</option>"; }
																}
																?>
															</select>
														</div>
													</div>
												</div>
												
											</div>
										</div>
									</div>
									
								</div>
							</div>
						</div>
					</div>
					
					<div class='card'>
						<div class='card-body'>
							<div class="row mb-2">
								<div class="col-md-12">
									<div class="form-group">
										<label for="subject" class="form-label border-start border-5 border-primary ps-1">Subject</label>
										<input type="text" class="form-control form-control-sm" name="subject" id="subject" value='<?=$subject;?>' required>
									</div>
								</div>
							</div>
							<input id='actdetailid_delete' type='hidden' name='actdetailid_delete' value='' />
							<div class='row mb-3'>
								<div class='col-12'>
									<button type='button' class='btn btn-sm btn-success' onclick='acttext_add()'>+ textarea</button>
								</div>
							</div>
							<div class='acttext mb-2'></div>
							<?php
							if($actdetailid != '') { // existing actdetail
								foreach($actdetailid as $key => $qindex) {
									$racttextid = $acttextid[$key];
							?>
							<div class="border border-primary row mb-2 p-2">
								<div class="row">
									<div class='col-12'>
										<button id='buttonx' class="btn btn-sm btn-danger mb-1" type="button" onclick='acttext_del(this, <?=$qindex;?>)'>X</button>
										<input type='hidden' name='actdetailid[]' value='<?=$qindex;?>'>
										<select name='acttextid[]' class='form-control form-control-sm mb-1 border border-1' style='border-color:blue !important;' >
											<?php
											foreach ($acttext as $data) {
												$qacttextid = $data['acttextid'];
												$qacttextcode = $data['acttextcode'];
												$qfulltext = $data['fulltext'];
												//echo "<option value='$qacttextid' selected>$qacttextcode - $qfulltext</option>";
												if( $racttextid == $qacttextid ) { echo "<option value='$qacttextid' selected>$qacttextcode - $qfulltext</option>"; }
												else { echo "<option value='$qacttextid'>$qacttextcode - $qfulltext</option>"; }
											}
											?>
										</select>
										<textarea class="form-control mb-1 editor" id="crmtextarea" name="textvalue[]"><?=$textvalue[$key];?></textarea>
									</div>
								</div>
							</div>
							<?php		
								}
							} 
							?>
						</div>
					</div>
					
					<!-- sparepart -->
					<div class='card'>
						<div class='card-body'>
							<div class="accordion accordion-flush mb-3" id="accordionSparepart">
								<div class="accordion-item">
									<h2 class="accordion-header" id="sparepartHeading">
										<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sparepart" 
											aria-expanded="true" aria-controls="sparepart">
										Sparepart Usage
										</button>
									</h2>
									<div id="sparepart" class="accordion-collapse collapse bg-white" aria-labelledby="sparepartHeading" data-bs-parent="#accordionSparepart">
										<div class="accordion-body">
											<input type='hidden' name='itxid_delete' id='itxid_delete' />
											
											<div class="d-flex flex-row justify-space-between align-items-center mb-3 mb-lg-2">
												
												<div class="col-12 col-lg-3 pt-lg-2 pb-lg-2 pe-lg-2">
													<div class="form-group">
														<label for="open" class="form-label">Transaction Datetime</label>
														<span style="color:#E72929;" id='datetimewarning'></span>
														<input type='text' class="form-control form-control-sm itxdate" value='<?=$closedate;?>' />
													</div>
												</div>
												
												<div class="col-12 col-lg-4 p-lg-2">
													<div class="form-group">
														<label for="open" class="form-label ">Destination</label>
														<span style="color:#E72929;" id='destwarning'></span>
														<select class='form-control form-select-sm select2 dest' id='destination'>
															<option value=''>-</option>
															<?php
															foreach($dests as $qid => $qname) {
																if($qid == "P|".$productid) { echo "<option value='$qid' selected>$qname</option>"; }
																else { echo "<option value='$qid'>$qname</option>"; }
															}
															?>										
														</select>
													</div>
												</div>
												
												<div class="col-12 col-lg-1 text-center p-lg-2">
													<button type='button' class='btn btn-sm btn-success mt-lg-3' id='swapButton'>
														<i class="fa-solid fa-right-left "></i>
													</button>
												</div>

												<div class="col-12 col-lg-4 p-lg-2">
													<div class="form-group">
														<label for="close" class="form-label">Origin</label>
														<span style="color:#E72929;" id='originwarning'></span>
														<select class='form-control form-select-sm select2 origin' id='origin'>
															<option value=''>-</option>
															<?php
															foreach($origins as $qid => $qname) {
																echo "<option value='$qid'>$qname</option>";
															}
															?>										
														</select>
													</div>
												</div>

											</div>

											<!-- <div class="row mb-1"> -->
											<div class="d-flex flex-row justify-space-between align-items-center mb-3 mb-lg-2">
												<div class="col-12 col-lg-2 pt-lg-2 pb-lg-2 pe-lg-2">
													<div class="form-group">
														<label for="close" class="form-label">
															Purpose &nbsp;
															
															<a class="btn btn-outline-success btn-sm p-1" href="https://services-summit.my.id/guidebook/view/1" role="button" onclick="window.open(this.href, 'Purpose Detail','width=900,height=800,toolbar=1,resizable=0'); return false;"> <i class="fa-solid fa-book"></i> Instruction </a>
														</label>
														<span style="color:#E72929;" id='purposewarning'></span>
														<select class='form-control form-control-sm purpose'>
															<option value=''>-</option>
															<?php
															foreach($purposes as $qid => $qval) {
																echo "<option value='$qid'>$qval</option>";
															}
															?>
														</select>
													</div>
												</div>
												<div class="col-12 col-lg-5 p-lg-2">
													<div class="form-group">
														<label for="open" class="form-label ">Catalog</label>
														<span style="color:#E72929;" id='unitgroupwarning'></span>
														<select class='form-control form-select-sm select2 unitgroupid'>
															<option value=''>-</option>
															<?php
															$unitgroups = array();
															foreach($unitgroup as $data) {
																$qunitgroupid = $data['unitgroupid'];
																$qproductname = $data['productname'];
																$qqty = $data['quantity'];
																$qunit = $data['unit'];
																$qbaseunit = $data['baseunit'];
																$qcatalognumber = $data['catalognumber'];
																if($qunit == $qbaseunit) { echo "<option value='$qunitgroupid'>[$qqty $qbaseunit] $qcatalognumber - $qproductname</option>"; }
																else { echo "<option value='$qunitgroupid'>[$qqty $qbaseunit][$qunit] $qcatalognumber - $qproductname</option>"; }
																$unitgroups[$qunitgroupid]=$qproductname;
															}
															?>
														</select>
													</div>
												</div>
												<div class="col-12 col-lg-1 p-lg-2">
													<div class="form-group">
														<label for="close" class="form-label ">Lot#</label>
														<input type='text' class="form-control form-control-sm lotnumber" />
													</div>
												</div>
												<div class="col-12 col-lg-1 p-lg-2">
													<div class="form-group">
														<label for="close" class="form-label ">Qty#</label>
														<input type='text' class="form-control form-control-sm qty" />
													</div>
												</div>
												<div class="col-12 col-lg-2 p-lg-2">
													<div class="form-group">
														<label for="close" class="form-label">Condition</label>
														<select class='form-control form-control-sm condition'>
															<option value=''>-</option>
															<?php
															foreach($conditions as $qid => $qval) {
																echo "<option value='$qid'>$qval</option>";
															}
															?>
														</select>
													</div>
												</div>
												<div class="d-grid gap-2 col-12 col-lg-1 mt-3 p-lg-2 text-center">
													<button type='button' class='btn btn-sm btn-success' onclick='saveRow();' >Add</button>
												</div>
											</div>
											<hr />
											<div class='table-responsive'>
												<table class='table table-bordered table-sm' id='itx_table'>
													<thead>
														<tr> 
															<th style='width:23.3%;'>Dest.</th> 
															<th style='width:23.3%;'>Orig.</th> 
															<th style='width:23.3%;'>Catalog</th> 
															<th style='width:5%;'>Lot#.</th> 
															<th style='width:5%;'>Qty.</th> 
															<th style='width:5%;'>Cond.</th> 
															<th style='width:5%;'>Purpose</th>
															<th style='width:10%;'>Trans. Date</th>
															<th></th>
														</tr>
													</thead>
													<tbody>
														
														<?php
														if(isset($invtrans)) {
															foreach($invtrans as $data) {
																$itxid = $data['itxid'];
																$qdest = $data['desttype']."|".$data['destid'];
																$qdest = $dests[$qdest];
																$qorigin = $data['origtype']."|".$data['origid'];
																$qorigin = $origins[$qorigin];
																$qcatalogname = $unitgroups[$data['unitgroupid']];
																$qlotnumber = $data['lotnumber'];
																$qqty = $data['qty'];
																$qpurpose = $purposes[$data['purpose']];
																$qitxdate = $data['itxdate'];
																if($data['conditions'] != '') { $qconditions = $conditions[$data['conditions']]; }
																else { $qconditions = ''; }
																echo "<tr> <td>$qdest</td> <td>$qorigin</td> <td>$qcatalogname</td> <td>$qlotnumber</td> <td>$qqty</td> <td>$qconditions</td> <td>$qpurpose</td> <td>$qitxdate</td>".
																	"<td class='text-center'> <button type='button' class='btn btn-sm btn-warning' onclick='deleteRow(this, $itxid)'>delete</button> </td>".
																	"</tr>";
															}
														}
														?>
													</tbody>
												</table>
											</div>
										</div>	
									</div>
								</div>
							</div>
						</div>
					</div>
					
					<div class='card'>
						<div class='card-body'>
							<div class="row mb-2">
								<div class="col-md-12">
									<label for="drag-drop-area" class="form-label border-start border-5 border-primary ps-1">Attachment</label>
									<input type="text" class='form-control form-control-sm' name="attachment" id="attachment" value="<?=$attachment;?>" />
									<div id="drag-drop-area"></div>
								</div>
							</div>
						</div>
						<div class="card-footer">
							<button type="submit" name="submit" class="btn btn-info float-end">Save</button>
							<!-- <button type="submit" name="submit" formaction="savesend" class="btn btn-info float-end">Save and send</button> -->
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

<?= $this->endSection() ?>

<?= $this->section('script') ?>
<script>
$(document).ready(function() {
	$('.select2').select2({
		theme: 'bootstrap-5',
		width: '100%'
	});
	
});

// acttext
// hapus acttext
function acttext_del(e, actdetailid) {
	if(confirm('Are you sure?')) {
		e.parentNode.parentNode.parentNode.remove();
		var actdetailid = actdetailid.toString();
		var d = $('#actdetailid_delete');
		d.val(d.val()+' '+actdetailid);
		console.log(d.val());
	}
}

// config
// config = {
// 	selector:'textarea',
// 	promotion:false,
// 	menubar:false,
// 	paste_data_images:false,
// 	height:'250',
// 	content_style: "p { margin: 0; }",
// 	// plugins: 'lists',
// 	plugins: 'print preview powerpaste casechange importcss tinydrive searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link media mediaembed template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists checklist wordcount tinymcespellchecker a11ychecker imagetools textpattern noneditable help formatpainter permanentpen pageembed charmap tinycomments mentions quickbars linkchecker emoticons advtable export',
// 	toolbar: 'insertfile undo redo styles styleselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
// 	// plugins: "textcolor"
// 	//forced_root_block : 'pre'
// };
// tinymce.init(config);

// config
config = {
	selector:'textarea',
	height:'350',
	promotion:false,
	// forced_root_block : 'pre',
	paste_data_images:false,
	content_style: "p { margin: 0; }",
	plugins: 'preview importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen link template codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount charmap emoticons',
	menubar: 'file edit view insert format tools table',
	toolbar: 'undo redo | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | template link anchor codesample',
	autosave_ask_before_unload: true,
	autosave_interval: '30s',
	automatic_uploads: false,
	setup: function (editor) {
		editor.on('keydown', function (e) {
		  if (e.keyCode === 33 || e.keyCode === 34) {
			e.preventDefault();
		  }
		});
	}
};
tinymce.init(config);

// buat textarea baru
function acttext_add() {
	$.get("<?=base_url();?>/activities/newtextarea", function(data) {
		$('.acttext').prepend(data);
		tinymce.init(config);
	})
}

$('#actby').change(function() {
	var actby=this.value;
	if(actby == 'P') {
		var siteid=$('#siteid').val();
		$.get("<?=base_url();?>/activities/getproduct/"+siteid, function(data) {
			$('#actby_item').html(data);
			$('.select2').select2({
				theme: 'bootstrap-5',
				width: '100%'
			});
		})
	} else if (actby == 'V') {
		$.get("<?=base_url();?>/activities/getvendor/0", function(data) {
			$('#actby_item').html(data);
		})
	} else if (actby == 'C') {
		$.get("<?=base_url();?>/activities/getconsumable/0", function(data) {
			$('#actby_item').html(data);
			$('.select2').select2({
				theme: 'bootstrap-5',
				width: '100%'
			});
		})
	}else {
		$('#actby_item').html('');
	}
	
})

if ($('#status').val() == 'R') {
	$("#opendate").prop('disabled', false); $("#actid_ref").prop('disabled', true); $(".closedate").prop('disabled', false);
}

// disable closedate if open
// disabble closedate, opendate, useridowner if pending
$('#status').change(function() {
    if(this.value=='R' || this.value=='r'){ $("#opendate").prop('disabled', false);  $(".closedate").prop('disabled', false);}	
	else if(this.value=='O'){$(".closedate").prop('disabled', true); $("#opendate").prop('disabled', false); } 
	else if(this.value=='P'){$("#userid_owner").prop('disabled', true); $("#opendate").prop('disabled', true); $(".closedate").prop('disabled', true); }
	else { $(".closedate").prop('disabled', false); $("#opendate").prop('disabled', false);}
})

$("#maintenance").prop('disabled', true); $("#calibration").prop('disabled', true); $("#installation").prop('disabled', true); $("#offreport").prop('disabled', true); $("#training").prop('disabled', true);
$('#acttypeid').change(function() {
    if (this.value=='5'){ $("#maintenance").prop('disabled', false); $("#calibration").prop('disabled', true); $("#installation").prop('disabled', true); $("#offreport").prop('disabled', true); $("#training").prop('disabled', true);}
	else if (this.value=='3'){ $("#maintenance").prop('disabled', true); $("#calibration").prop('disabled', false); $("#installation").prop('disabled', false); $("#offreport").prop('disabled', false); $("#training").prop('disabled', false); } 
	else { $("#maintenance").prop('disabled', true); $("#calibration").prop('disabled', true); $("#installation").prop('disabled', true); $("#offreport").prop('disabled', true); $("#training").prop('disabled', true);}
})

// reportdate change => opendate.value = reportdate.value 
$('#reportdate').change(function() {
	$('#opendate').val(this.value);
})

// closedate change => itxdate
$('.closedate').change(function() {
	$('.itxdate').val(this.value);
})

//InvTrans
function deleteRow(btn, itxid) {
	if(confirm('Are you sure?')) {
		var row = btn.parentNode.parentNode;
		row.parentNode.removeChild(row);
		var itxid = itxid.toString();
		var d = $('#itxid_delete');
		d.val(d.val()+' '+itxid);
		console.log(d.val());
	}
}

function saveRow() {
	var dest = $('.dest').val();
	var desttext = $('.dest option:selected').text();
	var origin = $('.origin').val();
	var origintext = $('.origin option:selected').text();
	var unitgroupid = $('.unitgroupid').val();
	var unitgroupidtext = $('.unitgroupid option:selected').text();
	var purpose = $('.purpose').val();
	var purposetext = $('.purpose option:selected').text();
	var lotnumber = $('.lotnumber').val();
	var qty = $('.qty').val();
	var condition = $('.condition').val();
	var conditiontext = $('.condition option:selected').text();
	var itxdate = $('.itxdate').val();
	
	let datetimeWarning = document.getElementById('datetimewarning');
	let destWarning = document.getElementById('destwarning');
	let originWarning = document.getElementById('originwarning');
	let purposeWarning = document.getElementById('purposewarning');
	let unitgroupWarning = document.getElementById('unitgroupwarning');
	// Digunakan untuk mengecek apakah kolom sudah diisi atau belum
	if (itxdate == "" || dest == "" || origin == "" || purpose == "" || unitgroupid == "") {
		if (itxdate == ""){datetimeWarning.textContent  = "*Tidak boleh kosong";} else {datetimeWarning.textContent  = "";}
		if (dest == ""){destWarning.textContent  = "*Tidak boleh kosong";} else {destWarning.textContent  = "";}
		if (origin == ""){originWarning.textContent  = "*Tidak boleh kosong";} else {originWarning.textContent  = "";}
		if (purpose == ""){purposeWarning.textContent  = "*Tidak boleh kosong";} else {purposeWarning.textContent  = "";}
		if (unitgroupid == ""){unitgroupWarning.textContent  = "*Tidak boleh kosong";} else {unitgroupWarning.textContent  = "";}
	} else {
		datetimeWarning.textContent  = "";
		destWarning.textContent  = "";
		originWarning.textContent  = "";
		purposeWarning.textContent  = "";
		unitgroupWarning.textContent  = "";

		var newRow = "<tr> <input type='hidden' name='dests[]' value='"+dest+"'> <input type='hidden' name='origins[]' value='"+origin+"' /> <input type='hidden' name='unitgroupid[]' value='"+unitgroupid+
			"' /> <input type='hidden' name='lotnumber[]' value='"+lotnumber+"' /> <input type='hidden' name='qty[]' value='"+qty+"' />"+" <input type='hidden' name='conditions[]' value='"+condition+
			"' /> <input type='hidden' name='purpose[]' value='"+purpose+"'> <input type='hidden' name='itxdate[]' value='"+itxdate+"' />"+
			" <td>"+desttext+"</td> <td>"+origintext+"</td> <td>"+unitgroupidtext+"</td> <td>"+lotnumber+"</td> <td>"+qty+"</td> <td>"+conditiontext+"</td> <td>"+purposetext+"</td> <td>"+itxdate+"</td>"+
			" <td class='text-center'> <button type='button' class='btn btn-sm btn-warning' onclick='deleteRow(this, 0)'>delete</button> </td> </tr>";
		$("#itx_table").append(newRow);
		//$('.origin').val('');
		$('.unitgroupid').val('');
		$('.lotnumber').val('');
		$('.qty').val('');
		$('.condition').val('');
		$('.purpose').val('');
		$('.select2').select2({
			theme: 'bootstrap-5',
			width: '100%'
		});
	}
}

// flatpickr report open close dt
flatpickr("#reportdate", { allowInput: true, enableTime: true, dateFormat: "Y-m-d\TH:i", time_24hr: true });
flatpickr("#opendate", { allowInput: true, enableTime: true, dateFormat: "Y-m-d\TH:i", time_24hr: true });
flatpickr(".closedate", { allowInput: true, enableTime: true, dateFormat: "Y-m-d\TH:i", time_24hr: true});
flatpickr(".itxdate", { allowInput: true, enableTime: true, dateFormat: "Y-m-d\TH:i", time_24hr: true});

let btnSwap = document.getElementById('swapButton');
let destination = document.getElementById('destination');
let origin = document.getElementById('origin');
btnSwap.addEventListener('click', () => {

	valDestination = destination.value;
	valOrigin = origin.value;
	
	if (valDestination != valOrigin) { 

		destination.value = valOrigin;
		origin.value      = valDestination;

		triggerChange(destination);
		triggerChange(origin);
	}
});
function triggerChange(element){
	let changeEvent = new Event ('change');
	element.dispatchEvent(changeEvent);
}
</script>

<script src="<?=base_url();?>/assets/uppy/uppy-full.js"></script>	
<?= $this->endSection() ?>
