<?php
include 'header.php';

require 'permission.php';
requireView('remark-report');

$bdd = new DB();
?>
<div class="content-wrapper">

	<section class="content-header"><div class="container-fluid"></div></section>

	<section class="content">
		<div class="container-fluid">
			<div class="col-lg-12">
            <div class="card">
			<div class="card-header"><h3 class="card-title">Last Followup Remark Report</h3></div>
			<!--<div id="test_data"></div>-->
                <form method="post">
					<div class="card-body">
						<div class="form-group">
							<div class="input-group">
								<button type="button" class="btn btn-default float-right" id="daterange-btn">
									<i class="far fa-calendar-alt"></i> Select Date
									<i class="fas fa-caret-down"></i>
								</button>

								<!-- Hidden fields -->
								<input type="hidden" name="start_date" id="start_date">
								<input type="hidden" name="end_date" id="end_date">
							</div>
						</div>
					</div>

					<div class="card-footer">
						<button type="submit" name="get-report" class="btn btn-primary">Submit</button>
					</div>
				</form>

            </div>            
          </div>
		  
		  <div class="row">
			  <div class="col-lg-12">
				<div class="card">
					<div class="card-header"><h3 class="card-title">Remark Report</h3></div>
					<div class="card-body">
						<div id="remark_report_div"></div>
					</div>
				</div>            
			  </div>
		  </div>
		  
		</div>
	</section>

</div>

<?php
include 'footer.php';
?>
<script>

$(function () {

    $('#daterange-btn').daterangepicker({
        ranges: {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        startDate: moment().subtract(29, 'days'),
        endDate: moment()
    }, function (start, end) {

        // Set values for PHP
        $('#start_date').val(start.format('YYYY-MM-DD'));
        $('#end_date').val(end.format('YYYY-MM-DD'));

        // Optional: change button text
        $('#daterange-btn').html(
            '<i class="far fa-calendar-alt"></i> ' +
            start.format('DD-MM-YYYY') + ' to ' + end.format('DD-MM-YYYY') +
            ' <i class="fas fa-caret-down"></i>'
        );
    });

});

</script>

<?php


if (isset($_POST['get-report'])) {
	$status_where="";
	
	if (($_GET['status'] ?? '') == 'lost') {
		$status_where=" service_status='lost' ";
	}else{
		$status_where=" service_status='pending' ";
	}
	
	$query_str="SELECT s.customer_name,s.mobile_no,s.registration_no,s.chassis_no, sf.last_followup_date,sf.remark,sf.service_type,sf.call_detail FROM service_followup AS sf LEFT JOIN service AS s ON s.id = sf.service_id WHERE $status_where";
	
    $start = $_POST['start_date'];
    $end   = $_POST['end_date'];
	
	$remark_rows=array();

    if ($start === $end) {
		if($current_date==$start){
			$remark_rows=$bdd->getAll("$query_str AND last_followup_date=?",[$start]);
			/*if (!empty($status_where)) {
				$remark_rows=$bdd->getAll("$query_str AND last_followup_date=?",[$start]);
			}else{
				$remark_rows=$bdd->getAll("$query_str last_followup_date=?",[$start]);
			}*/
		}else{
			$remark_rows=$bdd->getAll("$query_str AND last_followup_date=?",[$end]);
			/*if (!empty($status_where)) {
				$remark_rows=$bdd->getAll("$query_str AND last_followup_date=?",[$end]);
			}else{
				$remark_rows=$bdd->getAll("$query_str last_followup_date=?",[$end]);
			}*/
		}
    }else{
		$remark_rows = $bdd->getAll("$query_str AND sf.last_followup_date BETWEEN ? AND ?",[$start, $end]);
		/*if (!empty($status_where)) {
			$remark_rows = $bdd->getAll("$query_str AND sf.last_followup_date BETWEEN ? AND ?",[$start, $end]);
		}else{
			$remark_rows = $bdd->getAll("$query_str sf.last_followup_date BETWEEN ? AND ?",[$start, $end]);
		}*/
	}
		
	$grouped = [];

foreach ($remark_rows as $row) {

    // ✅ Use a non-empty unique key
    $key = $row['chassis_no'];
	$time_result="";
	if(!empty($row['call_detail'])){
		$time_data = json_decode($row['call_detail'], true);
		$time_result = "Start at {$time_data['started_at']} , End at {$time_data['ended_at']} , Duration:{$time_data['duration']}";
	}

    if (!isset($grouped[$key])) {
        $grouped[$key] = [
            'customer_name'   => $row['customer_name'],
            'mobile_no'       => $row['mobile_no'],
            'registration_no' => $row['registration_no'],
            'chassis_no'      => $row['chassis_no'],
            'followups'       => []
        ];
    }

    $grouped[$key]['followups'][] = [
        'date' => !empty($row['last_followup_date'])
            ? date('d-m-Y', strtotime($row['last_followup_date']))
            : null,
        'service_type' => $row['service_type'],
        'remark'       => $row['remark'],
		'call_detail'       => $time_result
    ];
}


	
	
	$_SESSION['excel_report'] = $grouped;
	
	echo "<script>window.open('export_excel-remark-report.php', '_blank');</script>";
	
	$remark_report_str="";
	$maxFollowups = 0;
	foreach ($grouped as $row) {
		$count = count($row['followups']);
		if ($count > $maxFollowups) {
			$maxFollowups = $count;
		}
	}

	$remark_report_str .= "<div class='table-responsive'><table id='remark_table' class='table table-bordered table-striped text-nowrap'>";

	$remark_report_str .= "<thead><tr>
			<th>Customer Name</th>
			<th>Mobile No</th>
			<th>Vehicle</th>
			<th>Chassis No</th>";

	for ($i = 1; $i <= $maxFollowups; $i++) {
		$remark_report_str .= "<th>Followup Date {$i}</th>";
		$remark_report_str .= "<th>Service Type {$i}</th>";
		$remark_report_str .= "<th>Remark {$i}</th>";
		$remark_report_str .= "<th>Detail {$i}</th>";
	}

	$remark_report_str .= "</tr></thead><tbody>";


	foreach ($grouped as $data) {

		$remark_report_str .= "<tr>";
		$remark_report_str .= "<td>{$data['customer_name']}</td>";
		$remark_report_str .= "<td>{$data['mobile_no']}</td>";
		$remark_report_str .= "<td>{$data['registration_no']}</td>";
		$remark_report_str .= "<td>{$data['chassis_no']}</td>";

		for ($i = 0; $i < $maxFollowups; $i++) {

			if (isset($data['followups'][$i])) {
				$remark_report_str .= "<td>{$data['followups'][$i]['date']}</td>";
				$remark_report_str .= "<td>{$data['followups'][$i]['service_type']}</td>";
				$remark_report_str .= "<td>{$data['followups'][$i]['remark']}</td>";
				$remark_report_str .= "<td>{$data['followups'][$i]['call_detail']}</td>";
			} else {
				$remark_report_str .= "<td></td><td></td><td></td>";
			}
		}

		$remark_report_str .= "</tr>";
	}

	$remark_report_str .= "</tbody></table></div>";
	
	echo "<script>document.getElementById('remark_report_div').innerHTML = " . json_encode($remark_report_str) . ";</script>";


$jsonRemark = json_encode($remark_report_str);

$jsonRemark = json_encode($remark_report_str);

echo <<<JS
<script>
document.getElementById('remark_report_div').innerHTML = $jsonRemark;

$(function () {

    if ($.fn.DataTable.isDataTable('#remark_table')) {
        $('#remark_table').DataTable().destroy();
    }

    $('#remark_table').DataTable({
        paging: true,
        searching: true,
        ordering: true,
        lengthChange: true,
        autoWidth: false,
        scrollX: true,
        responsive: false
    });

});
</script>
JS;

}
$bdd->disconnect();
?>