<?php
include 'header.php';

require 'permission.php';
requireView('upload-data');

require_once __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

$successMsg = '';
$errorMsg   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	
	$report=array();
	$earray=array();
	
	$bdd = new DB();

    if (!isset($_FILES['service_file']) || $_FILES['service_file']['error'] === UPLOAD_ERR_NO_FILE) {
        $errorMsg = 'Please select a file to upload.';
    } else {
        $file = $_FILES['service_file'];

        // Basic error check
        if ($file['error'] !== UPLOAD_ERR_OK) {
            switch ($file['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $errorMsg = 'File is too large.';
                    break;
                default:
                    $errorMsg = 'Upload error. Code: ' . $file['error'];
            }
        } else {
            // ✅ Settings
            $maxSize           = 50 * 1024 * 1024; // 5 MB
            $allowedExtensions = ['xls','xlsx']; // adjust as needed

            $originalName = $file['name'];
            $ext          = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

            // Size check
            if ($file['size'] > $maxSize) {
                $errorMsg = 'File is larger than 5 MB.';
            }
            // Extension check
            elseif (!in_array($ext, $allowedExtensions)) {
                $errorMsg = 'Invalid file type. Allowed: ' . implode(', ', $allowedExtensions);
            } else {
                // ✅ Safe filename
                $baseName    = pathinfo($originalName, PATHINFO_FILENAME);
                $safeBase    = preg_replace('/[^A-Za-z0-9_\-]/', '_', $baseName);
                $newFileName = $safeBase . '_' . time() . '.' . $ext;

                // ✅ Upload directory
                $uploadDir = web_constant::TEMP_DIR;

                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }

                $targetPath = $uploadDir . $newFileName;

                if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                    $successMsg = 'File uploaded successfully as: ' . htmlspecialchars($newFileName);
					
					$spreadsheet = IOFactory::load($targetPath);
                    $sheet       = $spreadsheet->getActiveSheet();

                    $startRow = 2;
                    $highestRow = $sheet->getHighestRow();
					
					//echo "TEST";
					for ($rowIndex = $startRow; $rowIndex <= $highestRow; $rowIndex++) {
						$row = $sheet->rangeToArray(
							"A{$rowIndex}:K{$rowIndex}",
							null,     // nullValue
							true,     // calculate formulas
							false     // return as numeric index
						)[0];
	
						$invoice_date_str = trim((string)($row[0] ?? ''));
                        $customer_name = trim((string)($row[1] ?? ''));
						$address_1     = trim((string)($row[2] ?? ''));
                        $address_2     = trim((string)($row[3] ?? ''));
                        $city     = trim((string)($row[4] ?? ''));
                        $mobile_no     = trim((string)($row[5] ?? ''));
                        $product  = trim((string)($row[6] ?? ''));
                        $chassis_no    = trim((string)($row[7] ?? ''));
                        $engine_no     = trim((string)($row[8] ?? ''));
                        $institute    = trim((string)($row[9] ?? ''));
                        $financer     = trim((string)($row[10] ?? ''));
						
						
						$address=$address_1.", ".$address_2;
						$year=substr($invoice_date_str,6,4);
						$month=substr($invoice_date_str,3,2);
						$day=substr($invoice_date_str,0,2);
						$invoice_date=$year.'-'.$month.'-'.$day;
						
						if (!empty($chassis_no) && !empty($customer_name)) {
							$values=array($chassis_no);
							$service_row = $bdd->getOne("SELECT id FROM service WHERE chassis_no = ?",$values);
							
							if (empty($address)){
								$address = NULL;
							}
							if (empty($mobile_no)){
								$mobile_no = NULL;
							}
							if (empty($engine_no)){
								$engine_no = NULL;
							}
							
							if (empty($service_row)){
								
								if (empty($product)){
									$product = NULL;
								}else{
									$values=array($product);
									$product_row = $bdd->getOne("SELECT id FROM products WHERE name = ? LIMIT 1",$values);
									if(empty($product_row)){
										$values=array($product);
										$product_id = $bdd->lastId("INSERT INTO products (name) VALUES (?)",$values);
									}else{
										$product_id = $product_row['id'];
									}
								}
								
								if (empty($city)){
									$city = NULL;
								}else{
									$values=array($city);
									$city_row = $bdd->getOne("SELECT id FROM city WHERE name = ? LIMIT 1",$values);
									if(empty($city_row)){
										$values=array($city);
										$city_id = $bdd->lastId("INSERT INTO city (name) VALUES (?)",$values);
									}else{
										$city_id = $city_row['id'];
									}
								}
								
								
								if (empty($institute)){
									$institute = NULL;
								}else{
									$values=array($institute);
									$institute_row = $bdd->getOne("SELECT id FROM institute WHERE name = ? LIMIT 1",$values);
									if(empty($institute_row)){
										$values=array($institute);
										$institute_id = $bdd->lastId("INSERT INTO institute (name) VALUES (?)",$values);
									}else{
										$institute_id = $institute_row['id'];
									}
								}
								
								if (empty($financer)){
									$financer = NULL;
								}else{
									$values=array($financer);
									$financer_row = $bdd->getOne("SELECT id FROM financer WHERE name = ? LIMIT 1",$values);
									if(empty($financer_row)){
										$values=array($financer);
										$financer_id = $bdd->lastId("INSERT INTO financer (name) VALUES (?)",$values);
									}else{
										$financer_id = $financer_row['id'];
									}
								}
								
								$values=array($invoice_date,$customer_name,$product_id,$mobile_no,$address,$city_id,$chassis_no,$engine_no,$institute_id,$financer_id,'active');
								$last_id = $bdd->lastId("INSERT INTO `service` (`invoice_date`, `customer_name`, `product_id`, `mobile_no`,`address`,`city_id`, `chassis_no`, `engine_no`,`institute_id`,`financer_id`, `status`) VALUES (?,?,?,?,?,?,?,?,?,?,?)",$values);
								
								if($last_id != 0){
									$nfd_days=0;
									$service_days=0;
									$service_type="";
									for($followup_cnt=1;$followup_cnt<=4;$followup_cnt++){
										if($followup_cnt==1){
											$nfd_days=23;
											$service_days=30;
											$service_type="Free Service - 3W";
										}else if($followup_cnt==2){
											$nfd_days=68;
											$service_days=75;
											$service_type="Second free service-3W";
										}else if($followup_cnt==3){
											$nfd_days=113;
											$service_days=120;
											$service_type="Third free service-3W";
										}else if($followup_cnt==4){
											$nfd_days=153;
											$service_days=160;
											$service_type="Paid Periodic Service";
										}
										
										$next_followup_date=date('Y-m-d', strtotime($invoice_date. " + ".$nfd_days." days"));
										$service_date=date('Y-m-d', strtotime($invoice_date. " + ".$service_days." days"));
										
										
										$values=array($last_id,$next_followup_date,$service_type,$followup_cnt,$service_date,$_SESSION['user_id']);
										$bdd->execute("INSERT INTO `service_followup` (`service_id`, `next_followup_date`, `service_type`, `service_no`,`service_date`,`user_id`) VALUES (?,?,?,?,?,?)",$values);
										
										/*$earray=array("Result"=>"Updated","DATE"=>$invoice_date,"PRODUCT"=>$product,"CHASSIS_NO"=>$chassis_no,"SERVICE TYPE"=>$service_type);
										array_push($report,$earray);*/
									}
									$earray=array("Result"=>"Updated","CHASSIS NO"=>$chassis_no);
									array_push($report,$earray);
								}
							}else{
								$earray=array("Result"=>"Customer alrady added","CHASSIS NO"=>$chassis_no);
								array_push($report,$earray);
							}
						}else{
							$earray=array("Result"=>"Customer name or chassis number is empty in excel file","CHASSIS_NO"=>$chassis_no);
							array_push($report,$earray);
						}
					}
					
					if (file_exists($targetPath)) {
						unlink($targetPath);
					}
					
                } else {
                    $errorMsg = 'Failed to save uploaded file.';
                }
            }
        }
    }

$bdd->disconnect();

$_SESSION['excel_report'] = $report;

?>
<script>
window.open('export_excel.php', '_blank');
</script>
<?php
}
?>

<div class="content-wrapper">

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

  <section class="content">
    <div class="container-fluid d-flex justify-content-center">

      <div class="col-md-6 mx-auto">

        <div class="card card-primary">
          <!-- Gradient Header -->
          <div class="card-header bg-gradient-primary text-center position-relative">
            <h3 class="card-title w-100 mb-0">Upload Data</h3>

            <div class="card-tools" style="position:absolute; right:12px;font-size: large;">
				<span class="float-right badge bg-info"><a href="sample-file/upload-data-sample.xls">Sample</a></span>
            </div>
          </div>

          <div class="card-body">

            <!-- ✅ PHP messages -->
            <?php if (!empty($successMsg)): ?>
              <div class="alert alert-success alert-dismissible">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <?= htmlspecialchars($successMsg) ?>
              </div>
            <?php endif; ?>

            <?php if (!empty($errorMsg)): ?>
              <div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <?= htmlspecialchars($errorMsg) ?>
              </div>
            <?php endif; ?>

            <form id="serviceUploadForm" action="" method="POST" enctype="multipart/form-data">

              <!-- Drag & Drop Zone -->
              <div id="dropZone" class="upload-dropzone mb-3 text-center">
                <i class="fas fa-cloud-upload-alt fa-2x mb-2"></i>
                <p class="mb-1 font-weight-bold">Drag & drop your file here</p>
                <small class="text-muted d-block mb-1">or click below to select</small>
              </div>

              <!-- File Input + Button -->
              <div class="form-group mb-0">
                <label for="serviceFile">Choose File</label>
                <div class="input-group">
                  <div class="custom-file">
                    <input type="file" class="custom-file-input" id="serviceFile" name="service_file">
                    <label class="custom-file-label" for="serviceFile">Select file</label>
                  </div>
                  <div class="input-group-append">
                    <button id="uploadBtn" class="btn btn-primary" type="submit">
                      <i class="fas fa-upload mr-1"></i> Upload
                    </button>
                  </div>
                </div>
              </div>

              <!-- Progress Bar -->
              <div id="uploadProgressWrapper" class="progress mt-3 d-none">
                <div id="uploadProgressBar"
                     class="progress-bar progress-bar-striped progress-bar-animated"
                     role="progressbar"
                     style="width: 0%">
                </div>
              </div>

            </form>
          </div>

        </div>
      </div>

    </div>
  </section>

</div>

<style>
  .bg-gradient-primary {
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    color: #fff !important;
  }

  .upload-dropzone {
    border: 2px dashed rgba(0, 0, 0, 0.1);
    border-radius: 0.5rem;
    padding: 1.5rem;
    transition: all 0.2s ease-in-out;
    background: #f8f9fa;
    cursor: pointer;
  }

  .upload-dropzone.dragover {
    background: #e3f2fd;
    border-color: #007bff;
    transform: translateY(-1px);
    box-shadow: 0 0.5rem 1rem rgba(0, 123, 255, 0.15);
  }
</style>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    var fileInput          = document.getElementById('serviceFile');
    var fileLabel          = document.querySelector('label.custom-file-label[for="serviceFile"]');
    var dropZone           = document.getElementById('dropZone');
    var uploadBtn          = document.getElementById('uploadBtn');
    var form               = document.getElementById('serviceUploadForm');
    var progressWrapper    = document.getElementById('uploadProgressWrapper');
    var progressBar        = document.getElementById('uploadProgressBar');

    var defaultLabelText   = 'Select file';

    function updateFileLabel(file) {
      if (file) {
        fileLabel.textContent = file.name;
      } else {
        fileLabel.textContent = defaultLabelText;
      }
    }

    fileInput.addEventListener('change', function () {
      if (fileInput.files && fileInput.files.length > 0) {
        updateFileLabel(fileInput.files[0]);
      } else {
        updateFileLabel(null);
      }
    });

    dropZone.addEventListener('click', function () {
      fileInput.click();
    });

    ['dragenter', 'dragover'].forEach(function (eventName) {
      dropZone.addEventListener(eventName, function (e) {
        e.preventDefault();
        e.stopPropagation();
        dropZone.classList.add('dragover');
      });
    });

    ['dragleave', 'drop'].forEach(function (eventName) {
      dropZone.addEventListener(eventName, function (e) {
        e.preventDefault();
        e.stopPropagation();
        dropZone.classList.remove('dragover');
      });
    });

    dropZone.addEventListener('drop', function (e) {
      var files = e.dataTransfer.files;
      if (files && files.length > 0) {
        var dataTransfer = new DataTransfer();
        dataTransfer.items.add(files[0]);
        fileInput.files = dataTransfer.files;
        updateFileLabel(files[0]);
      }
    });

    form.addEventListener('submit', function () {
      uploadBtn.disabled = true;
      uploadBtn.innerHTML =
        '<span class="spinner-border spinner-border-sm mr-1" role="status" aria-hidden="true"></span> Uploading...';

      progressWrapper.classList.remove('d-none');
      progressBar.style.width = '0%';

      var progress = 0;
      var interval = setInterval(function () {
        progress = Math.min(progress + 10, 100);
        progressBar.style.width = progress + '%';

        if (progress >= 100) {
          clearInterval(interval);
        }
      }, 300);
    });
  });
</script>




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