<?php
ob_start();
include("db/cn.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

@$job_id = $_GET['job_id'];
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>ALFALAH INDUSTRIES</title>
    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
		 .form-control, label, td, option{
	  	font-weight:700;
	  	color:#000;
		}
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');
  $pr_id2 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
<?php
// AJAX handler for bulk save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $input = json_decode(file_get_contents("php://input"), true);
  if (isset($input['job_id']) && isset($input['steps'])) {
    $job_id = $input['job_id'];
    foreach ($input['steps'] as $st) {
      $step_process = $st['name'];
      $date = date('Y-m-d');
      $status = $st['status'];
      if ($status !== 'Process') {
        $query = "INSERT INTO job_status (job_id, step_process, status, date_time) VALUES ('$job_id', '$step_process', '$status', '$date') ON DUPLICATE KEY UPDATE status='$status', date_time='$date'";
        mysqli_query($connection, $query);
      }
    }
    echo "success";
    exit;
  }
}

// job id from request
$job_id = $_GET['job_id'];

// fetch job details
$r = mysqli_query($connection,"SELECT * FROM add_jobs WHERE job_id = '$job_id'");
$t = mysqli_fetch_array($r);
$job_start_date = $t['date_time']; // base job start date

// build steps dynamically from add_jobs
$steps = [];
$res_steps = mysqli_query($connection, "SELECT job_proces, noofdays FROM add_jobs WHERE job_id='$job_id'");
while ($row = mysqli_fetch_assoc($res_steps)) {
  $steps[] = [
    'name' => $row['job_proces'],
    'duration' => (int)$row['noofdays']
  ];
}

// fetch saved statuses
$saved_statuses = [];
$res = mysqli_query($connection, "SELECT step_process, status, date_time FROM job_status WHERE job_id='$job_id'");
while ($row = mysqli_fetch_assoc($res)) {
  $saved_statuses[$row['step_process']] = [
    'status' => $row['status'],
    'date_time' => $row['date_time']
  ];
}
?>

<div class="container-fluid">
  <div class="row">
    <div class="col-6">
      <h1 class="mb-0 text-gray-800" style="font-weight:700;">Job - Management Detail</h1>
    </div>
    <div class="col-6">
        <button id="saveAll" class="btn btn-primary px-4 font-weight-bold" style="float:right;">Save All</button>
    </div>
  </div>
</div>
 <hr>
    <div class="col-12">
        <a href="view_job.php?customer_name=<?php echo $t['customer_name'];; ?>" class="btn btn-dark"><i class="fas fa-arrow-left"></i></a>
    </div>
<br>
<div class="container">
  <table class="table table-bordered bg-white font-weight-bold text-capitalize text-center">
    <tr class="bg-dark text-white">
      <td class="text-white">Sr#</td>
      <td class="text-white">Job - ID#</td>
      <td class="text-white">Job - Date</td>
      <td class="text-white">Customer</td>
      <td class="text-white">Item Name</td>
      <td class="text-white">Item Size</td>
      <td class="text-white">Quantity</td>
      <td class="text-white">Delivery</td>
    </tr>
    <tr class="font-weight-bold" style="color:#000;">
      <td>1</td>
      <td><?php echo $t['job_id']; ?></td>
      <td><?php echo $t['date_time']; ?></td>
      <td><?php echo $t['customer_name']; ?></td>
      <td><?php echo $t['item_name']; ?></td>
      <td><?php echo $t['item_size']; ?></td>
      <td><?php echo $t['quantity']; ?></td>
      <td><?php echo $t['delivery_date']; ?></td>
    </tr>
  </table>
</div>

<div class="container">
  <input type="hidden" id="job_id" value="<?php echo $job_id; ?>">
  <table class="table table-bordered bg-white text-center">
    <thead class="table-dark">
      <tr>
        <th>Step</th>
        <th>Duration (Days)</th>
        <th style="background:#0A4657;">Complete In (Days)</th>
        <th>Overdue (Days)</th>
        <th>Status</th>
        <th>Job</th>
      </tr>
    </thead>
    <tbody id="jobTable" class="bg-white"></tbody>
  </table>
  
</div>





                <!-- /.container-fluid -->

            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

 
</div>    
</body>
<script>
const steps = <?php echo json_encode($steps); ?>;
const savedStatuses = <?php echo json_encode($saved_statuses); ?>;
const jobStartDate = new Date("<?php echo $job_start_date; ?>");

function dateDiffInDays(d1, d2) {
  return Math.floor((d2 - d1) / (1000 * 60 * 60 * 24));
}

function renderTable() {
  const tbody = document.getElementById('jobTable');
  tbody.innerHTML = '';
  let lastCompleteDate = jobStartDate;
  let nextStepShown = false;

  steps.forEach((step, index) => {
    let record = savedStatuses[step.name] || {};
    let status = record.status || 'Process';
    let completeDate = record.date_time ? new Date(record.date_time) : null;
    step.status = status;

    let completeIn = '';
    let overdueDays = '';

    if (status === 'Complete' && completeDate) {
      let diff = dateDiffInDays(lastCompleteDate, completeDate);
      completeIn = diff + ' ';
      overdueDays = diff > step.duration ? (diff - step.duration) + ' ' : '0';
      lastCompleteDate = completeDate;
    }

    if (status === 'Complete') {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${step.name}</td>
        <td>${step.duration}</td>
        <td>${completeIn}</td>
        <td>${overdueDays}</td>
        <td>Complete</td>
        <td><i class="fas fa-check text-success"></i></td>`;
      tbody.appendChild(row);
    } else if (!nextStepShown) {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${step.name}</td>
        <td>${step.duration}</td>
        <td>${completeIn}</td>
        <td>0</td>
        <td>
          <select class="form-control status-update" data-step="${index}">
            <option value="Process" ${status==='Process'?'selected':''}>Process</option>
            <option value="Complete" ${status==='Complete'?'selected':''}>Complete</option>
          </select>
        </td>
        <td><i class="fas fa-clock text-warning"></i></td>`;
      tbody.appendChild(row);
      nextStepShown = true;
    }
  });
}

// Save All button
const saveBtn = document.getElementById('saveAll');
saveBtn.addEventListener('click', () => {
  const jobId = document.getElementById('job_id').value;
  const data = steps
    .filter(step => step.status && step.status !== 'Process')
    .map(step => ({ name: step.name, status: step.status }));

  fetch(window.location.href, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ job_id: jobId, steps: data })
  })
    .then(res => res.text())
    .then(msg => {
      alert('Saved Successfully');
      location.reload();
    })
    .catch(err => console.error(err));
});

// Handle dropdown changes
window.addEventListener('change', (e) => {
  if (e.target.classList.contains('status-update')) {
    const stepIndex = e.target.dataset.step;
    const value = e.target.value;
    steps[stepIndex].status = value;
    savedStatuses[steps[stepIndex].name] = { status: value, date_time: new Date().toISOString().slice(0,10) };
    renderTable();
  }
});

renderTable();
</script>
 <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>

   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>