<?php
include('../config/config.php');
include('../config/session_check.php'); 

session_start();
$branch_id = $_SESSION['branch_id'];
// Fetch Active Customers
$result = $conn->query("SELECT id, lorry_name, reg_no, year_model, capacity, status FROM vehicles WHERE status='active' && branch_id='$branch_id'");
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Customer Master</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="../assets/css/style.css" rel="stylesheet">
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
    @media (max-width: 768px) {
        table thead { display: none; }
        table tbody tr { display: block; margin-bottom: 1rem; border: 1px solid #ccc; padding: 1rem; }
        table tbody td { display: flex; justify-content: space-between; padding: .5rem 0; border-bottom: 1px solid #ddd; }
        table tbody td:last-child { border-bottom: none; }
        table td::before { content: attr(data-label); font-weight: bold; }
    }
    </style>
    


</head>

<body>

  <!-- ======= Header ======= -->
<?php include('../config/header.php'); ?> // Include the header

  <!-- ======= Sidebar ======= -->

<?php include('../config/sidebar.php'); ?>
  <main id="main" class="main">

    <div class="pagetitle">
      <h1>Data Tables</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">Home</a></li>
          <li class="breadcrumb-item">Tables</li>
          <li class="breadcrumb-item active">Data</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

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

          <div class="card">
            <div class="card-body">
                
               
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vechile Master</title>
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h2>Vechile  Management  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addVehicleModal">Add Vehicle</button></h2>
   
   
        <table class="table datatable mt-3">
            <thead>
                <tr>
                    <th>Lorry Name</th>
                    <th>Reg No</th>
                    <th>Year Model</th>
                    <th>Capacity</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
               <tr>
    <td data-label="Lorry Name"><?php echo htmlspecialchars($row['lorry_name']); ?></td>
    <td data-label="Reg. No"><?php echo htmlspecialchars($row['reg_no']); ?></td>
    <td data-label="Year Model"><?php echo htmlspecialchars($row['year_model']); ?></td>
    <td data-label="Capacity"><?php echo htmlspecialchars($row['capacity']); ?></td>
    <td data-label="Status"><?php echo htmlspecialchars($row['status']); ?></td>
    <td data-label="Actions">
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editVehicleModal" onclick="editVehicle(<?php echo $row['id']; ?>)">Edit</button>
        <button onclick="deleteVehicle(<?php echo $row['id']; ?>)" class="btn btn-danger">Delete</button>
    </td>
</tr>

                <?php endwhile; ?>
            </tbody>
        </table>
</div>

<!-- Add Vehicle Modal -->
<div class="modal fade" id="addVehicleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Vehicle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addVehicleForm">
                    <div class="mb-3">
                        <label for="lorry_name" class="form-label">Lorry Name</label>
                        <input type="text" class="form-control" id="lorry_name" name="lorry_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="reg_no" class="form-label">Reg No</label>
                        <input type="text" class="form-control" id="reg_no" name="reg_no" required>
                    </div>
                    <div class="mb-3">
                        <label for="year_model" class="form-label">Year Model</label>
                        <input type="number" class="form-control" id="year_model" name="year_model" required>
                    </div>
                    <div class="mb-3">
                        <label for="capacity" class="form-label">Capacity</label>
                        <input type="text" class="form-control" id="capacity" name="capacity" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="submitAddVehicleForm()">Save</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Vehicle Modal -->
<div class="modal fade" id="editVehicleModal" tabindex="-1" aria-labelledby="editVehicleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editVehicleModalLabel">Edit Vehicle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editVehicleForm">
                    <input type="hidden" id="editVehicleId" name="id">
                    <div class="mb-3">
                        <label for="editLorryName" class="form-label">Lorry Name</label>
                        <input type="text" class="form-control" id="editLorryName" name="lorry_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="editRegNo" class="form-label">Reg No</label>
                        <input type="text" class="form-control" id="editRegNo" name="reg_no" required>
                    </div>
                    <div class="mb-3">
                        <label for="editYearModel" class="form-label">Year Model</label>
                        <input type="number" class="form-control" id="editYearModel" name="year_model" required>
                    </div>
                    <div class="mb-3">
                        <label for="editCapacity" class="form-label">Capacity</label>
                        <input type="text" class="form-control" id="editCapacity" name="capacity" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="submitEditVehicleForm()">Update Vehicle</button>
            </div>
        </div>
    </div>
</div>




            </div>  
          </div>

        </div>
      </div>
    </section>

  </main><!-- End #main -->
  
  
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>


// Function to submit Add Vehicle Form
function submitAddVehicleForm() {
    var form = document.getElementById("addVehicleForm");

    if (!form) {
        console.error("Error: Form with ID 'addVehicleForm' not found.");
        alert("Error: Add Vehicle Form not found.");
        return;
    }

    var formData = new FormData(form);
    formData.append("action", "add");

    console.log("Submitting Form Data:", formData);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "vehicle_actions.php", true);

    xhr.onload = function () {
        console.log("Server Response:", xhr.responseText);

        if (xhr.status === 200) {
            alert(xhr.responseText);
            document.getElementById("addVehicleModal").classList.remove("show");
            location.reload();
        } else {
            alert("Error adding vehicle.");
        }
    };

    xhr.onerror = function () {
        console.error("Request failed.");
        alert("Request failed. Please check your connection.");
    };

    xhr.send(formData);
}



// Function to submit Edit Vehicle Form
function submitEditVehicleForm() {
    var form = document.getElementById("editVehicleForm");
    var formData = new FormData(form);
    formData.append("action", "edit");

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "vehicle_actions.php", true);

    xhr.onload = function () {
        if (xhr.status === 200) {
            alert(xhr.responseText);
            document.getElementById("editVehicleModal").classList.remove("show");
            location.reload();
        } else {
            alert("Error updating vehicle.");
        }
    };

    xhr.onerror = function () {
        alert("Request failed. Please check your connection.");
    };

    xhr.send(formData);
}

// Function to fetch vehicle data for editing
function editVehicle(id) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "vehicle_actions.php?id=" + id, true);

    xhr.onload = function () {
        if (xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            document.getElementById("editVehicleId").value = id;
            document.getElementById("editLorryName").value = data.lorry_name;
            document.getElementById("editRegNo").value = data.reg_no;
            document.getElementById("editYearModel").value = data.year_model;
            document.getElementById("editCapacity").value = data.capacity;
            document.getElementById("editVehicleModal").classList.add("show");
        } else {
            alert("Error fetching vehicle data.");
        }
    };

    xhr.onerror = function () {
        alert("Request failed. Please check your connection.");
    };

    xhr.send();
}

// Function to delete a vehicle (set status to inactive)
function deleteVehicle(id) {
    if (confirm("Are you sure you want to delete this vehicle?")) {
        var formData = new FormData();
        formData.append("id", id);
        formData.append("action", "delete");

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "vehicle_actions.php", true);

        xhr.onload = function () {
            if (xhr.status === 200) {
                alert(xhr.responseText);
                location.reload();
            } else {
                alert("Error deleting vehicle.");
            }
        };

        xhr.onerror = function () {
            alert("Request failed. Please check your connection.");
        };

        xhr.send(formData);
    }
}


</script>
  <!-- ======= Footer ======= -->
  <?php include '../config/footer.php'; ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="../assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/vendor/chart.js/chart.umd.js"></script>
  <script src="../assets/vendor/echarts/echarts.min.js"></script>
  <script src="../assets/vendor/quill/quill.js"></script>
  <script src="../assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="../assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="../assets/js/main.js"></script>

</body>

</html>