<?php
include('../config/config.php');
include('../config/session_check.php'); 
$branch_id = $_SESSION['branch_id'];
// Fetch Active Customers
$result = $conn->query("SELECT 
    o.id, o.order_no,o.order_date, c.customer_name, o.site_name, o.execution_date,
    o.aggregate_12m_kg, o.aggregate_sand_kg, o.aggregate_20mm_1_kg, o.aggregate_20mm_2_kg,
    o.cement_cem1_kg, o.cement_cem2_kg,
    o.admixture_admix1_kg, o.admixture_admix2_kg, o.water_kg,
    o.order_quantity_m3, o.status,
    mp.name AS marketing_person_name
    FROM orders o
    JOIN customers c ON o.customer_id = c.id
    JOIN marketing_persons mp ON o.marketing_person_id = mp.id
    WHERE o.status='active' AND o.branch_id=$branch_id");
$customers = $conn->query("SELECT id, customer_name FROM customers WHERE status='active' AND branch_id=$branch_id");
$marketers = $conn->query("SELECT id, name FROM marketing_persons WHERE status='active' AND 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>CONCRETE ORDER FORM </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>CONCRETE ORDER FORM</h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addOrderModal">New Order</button>
     <table class="table datatable">
      <thead>
        <tr>
            <th>Order No</th>
            <th>Order/Execution Date</th>
            <th>Customer</th>
            <th>Site</th>
            
            <th>Marketing Person</th>
            <th>Quantity (m³)</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $result->fetch_assoc()): ?>
        <tr>
            <td><?= htmlspecialchars($row['order_no']); ?></td>
            <td><?= htmlspecialchars($row['order_date']).'/'.htmlspecialchars($row['execution_date']); ?></td>
            <td><?= htmlspecialchars($row['customer_name']); ?></td>
            <td><?= htmlspecialchars($row['site_name']); ?></td>
             <td><?= htmlspecialchars($row['marketing_person_name']); ?></td>
         
            <td><?= htmlspecialchars($row['order_quantity_m3']); ?> m³</td>
            <td>
               <button onclick="viewOrder(<?= $row['id']; ?>)" class="btn btn-info btn-sm">View</button>
                <button onclick="editOrder(<?= $row['id']; ?>)" class="btn btn-warning btn-sm">Edit</button>
                <button onclick="deleteOrder(<?= $row['id']; ?>)" class="btn btn-danger btn-sm">Delete</button>
            </td>
        </tr>
        <?php endwhile; ?>
    </tbody>
    </table>
</div>

<!-- Add Order Modal -->
<div class="modal fade" id="addOrderModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">New Order</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="addOrderForm">
          <div class="mb-3">
            <label for="customer_id" class="form-label">Customer Name</label>
            <select class="form-control" id="customer_id" name="customer_id" required>
              <option value="">Select Customer</option>
              <?php 
              $customers = $conn->query("SELECT id, customer_name FROM customers WHERE status='active'");
              while ($row = $customers->fetch_assoc()): ?>
                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['customer_name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="mb-3">
            <label for="marketing_person_id" class="form-label">Marketing Person</label>
            <select class="form-control" id="marketing_person_id" name="marketing_person_id" required>
              <option value="">Select Marketing Person</option>
              <?php 
              $marketers = $conn->query("SELECT id, name FROM marketing_persons WHERE status='active'");
              while ($row = $marketers->fetch_assoc()): ?>
                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>

          <div class="mb-3">
            <label for="execution_date" class="form-label">Execution Date</label>
            <input type="date" class="form-control" id="execution_date" name="execution_date" required>
          </div>

          <div class="mb-3">
            <label for="site_name" class="form-label">Site Name</label>
            <input type="text" class="form-control" id="site_name" name="site_name" required>
          </div>

          <h5>Aggregate (KG)</h5>
          <div class="row">
            <div class="col"><label>12MM</label><input type="number" class="form-control" name="aggregate_12m_kg"></div>
            <div class="col"><label>Sand</label><input type="number" class="form-control" name="aggregate_sand_kg"></div>
            <div class="col"><label>20MM (1)</label><input type="number" class="form-control" name="aggregate_20mm_1_kg"></div>
            <div class="col"><label>20MM (2)</label><input type="number" class="form-control" name="aggregate_20mm_2_kg"></div>
          </div>

          <h5 class="mt-3">Cement (KG)</h5>
          <div class="row">
            <div class="col"><label>CEM1</label><input type="number" class="form-control" name="cement_cem1_kg"></div>
            <div class="col"><label>CEM2</label><input type="number" class="form-control" name="cement_cem2_kg"></div>
          </div>

          <h5 class="mt-3">Admixture (KG)</h5>
          <div class="row">
            <div class="col"><label>ADMIX1</label><input type="number" class="form-control" name="admixture_admix1_kg"></div>
            <div class="col"><label>ADMIX2</label><input type="number" class="form-control" name="admixture_admix2_kg"></div>
          </div>

          <h5 class="mt-3">Water (KG)</h5>
          <div class="row">
            <div class="col"><label>Water</label><input type="number" class="form-control" name="water_kg"></div>
          </div>

          <div class="mb-3 mt-3">
            <label for="order_quantity_m3" class="form-label">Order Quantity (m³)</label>
            <input type="number" class="form-control" id="order_quantity_m3" name="order_quantity_m3" 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="submitAddOrderForm()">Save</button>
      </div>
    </div>
  </div>
</div>


<!-- View Order Modal -->
<div class="modal fade" id="viewOrderModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">View Order Details</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-6"><strong>Order No:</strong> <span id="viewOrderNo"></span></div>
          <div class="col-md-6"><strong>Order Date:</strong> <span id="viewOrderDate"></span></div>
        </div>
        <div class="row">
          <div class="col-md-6"><strong>Customer:</strong> <span id="viewCustomerName"></span></div>
          <div class="col-md-6"><strong>Marketing Person:</strong> <span id="viewMarketingPerson"></span></div>
        </div>
        <div class="row">
          <div class="col-md-6"><strong>Execution Date:</strong> <span id="viewExecutionDate"></span></div>
          <div class="col-md-6"><strong>Site Name:</strong> <span id="viewSiteName"></span></div>
        </div>
        <hr>
        <h6>Materials (KG)</h6>
        <div class="row">
          <div class="col-md-3"><strong>12MM:</strong> <span id="viewAggregate12mKg"></span></div>
          <div class="col-md-3"><strong>Sand:</strong> <span id="viewAggregateSandKg"></span></div>
          <div class="col-md-3"><strong>20MM (1):</strong> <span id="viewAggregate20mm1Kg"></span></div>
          <div class="col-md-3"><strong>20MM (2):</strong> <span id="viewAggregate20mm2Kg"></span></div>
        </div>
        <div class="row mt-2">
          <div class="col-md-3"><strong>CEM1:</strong> <span id="viewCementCEM1Kg"></span></div>
          <div class="col-md-3"><strong>CEM2:</strong> <span id="viewCementCEM2Kg"></span></div>
          <div class="col-md-3"><strong>ADMIX1:</strong> <span id="viewAdmixtureAdmix1Kg"></span></div>
          <div class="col-md-3"><strong>ADMIX2:</strong> <span id="viewAdmixtureAdmix2Kg"></span></div>
        </div>
        <div class="row mt-2">
          <div class="col-md-3"><strong>Water:</strong> <span id="viewWaterKg"></span></div>
          <div class="col-md-3"><strong>Order Qty (m³):</strong> <span id="viewOrderQuantity"></span></div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>




<div class="modal fade" id="editOrderModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Order</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="editOrderForm">
          <input type="hidden" id="editOrderId" name="id">

          <div class="mb-3">
            <label for="editCustomerId" class="form-label">Customer Name</label>
            <select class="form-control" id="editCustomerId" name="customer_id" required>
              <option value="">Select Customer</option>
              <?php
              $customers = $conn->query("SELECT id, customer_name FROM customers WHERE status='active'");
              while ($row = $customers->fetch_assoc()) {
                echo "<option value='{$row['id']}'>" . htmlspecialchars($row['customer_name']) . "</option>";
              }
              ?>
            </select>
          </div>

         <div class="mb-3">
    <label for="editMarketingPersonId" class="form-label">Marketing Person</label>
    <select class="form-control" id="editMarketingPersonId" name="marketing_person_id" required>
        <option value="">Select Marketing Person</option>
        <?php 
        $marketers = $conn->query("SELECT id, name FROM marketing_persons WHERE status='active'");
        while ($row = $marketers->fetch_assoc()): ?>
            <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['name']) ?></option>
        <?php endwhile; ?>
    </select>
</div>

          <div class="mb-3">
            <label for="editExecutionDate" class="form-label">Execution Date</label>
            <input type="date" class="form-control" id="editExecutionDate" name="execution_date" required>
          </div>

          <div class="mb-3">
            <label for="editSiteName" class="form-label">Site Name</label>
            <input type="text" class="form-control" id="editSiteName" name="site_name" required>
          </div>

          <h5>Aggregate (KG)</h5>
          <div class="row">
            <div class="col">
              <label>12MM</label>
              <input type="number" class="form-control" id="editAggregate12mKg" name="aggregate_12m_kg">
            </div>
            <div class="col">
              <label>Sand</label>
              <input type="number" class="form-control" id="editAggregateSandKg" name="aggregate_sand_kg">
            </div>
            <div class="col">
              <label>20MM (1)</label>
              <input type="number" class="form-control" id="editAggregate20mm1Kg" name="aggregate_20mm_1_kg">
            </div>
            <div class="col">
              <label>20MM (2)</label>
              <input type="number" class="form-control" id="editAggregate20mm2Kg" name="aggregate_20mm_2_kg">
            </div>
          </div>

          <h5 class="mt-3">Cement (KG)</h5>
          <div class="row">
            <div class="col">
              <label>CEM1</label>
              <input type="number" class="form-control" id="editCementCEM1Kg" name="cement_cem1_kg">
            </div>
            <div class="col">
              <label>CEM2</label>
              <input type="number" class="form-control" id="editCementCEM2Kg" name="cement_cem2_kg">
            </div>
          </div>

          <h5 class="mt-3">Admixture (KG)</h5>
          <div class="row">
            <div class="col">
              <label>ADMIX1</label>
              <input type="number" class="form-control" id="editAdmixtureAdmix1Kg" name="admixture_admix1_kg">
            </div>
            <div class="col">
              <label>ADMIX2</label>
              <input type="number" class="form-control" id="editAdmixtureAdmix2Kg" name="admixture_admix2_kg">
            </div>
          </div>

          <h5 class="mt-3">Water (KG)</h5>
          <div class="row">
            <div class="col">
              <label>Water</label>
              <input type="number" class="form-control" id="editWaterKg" name="water_kg">
            </div>
          </div>

          <h5 class="mt-3">Order Quantity (m³)</h5>
          <div class="mb-3">
            <input type="number" class="form-control" id="editOrderQuantity" name="order_quantity_m3" 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="submitEditOrderForm()">Update Order</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 Order Form
function submitAddOrderForm() {
    var formData = new FormData(document.getElementById("addOrderForm"));
    formData.append("action", "add");

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

    xhr.onload = function () {
        alert(xhr.responseText);
        document.getElementById("addOrderModal").classList.remove("show");
        location.reload();
    };

    xhr.onerror = function () {
        alert("Error adding order. Please check your network.");
    };

    xhr.send(formData);
}

function editOrder(id) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "order_actions.php?action=view&id=" + id, true);

  xhr.onload = function () {
    if (xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);

      document.getElementById("editOrderId").value = id;
      document.getElementById("editCustomerId").value = data.customer_id;
      document.getElementById("editMarketingPersonId").value = data.marketing_person_id;
      document.getElementById("editExecutionDate").value = data.execution_date;
      document.getElementById("editSiteName").value = data.site_name;
      document.getElementById("editAggregate12mKg").value = data.aggregate_12m_kg;
      document.getElementById("editAggregateSandKg").value = data.aggregate_sand_kg;
      document.getElementById("editAggregate20mm1Kg").value = data.aggregate_20mm_1_kg;
      document.getElementById("editAggregate20mm2Kg").value = data.aggregate_20mm_2_kg;
      document.getElementById("editCementCEM1Kg").value = data.cement_cem1_kg;
      document.getElementById("editCementCEM2Kg").value = data.cement_cem2_kg;
      document.getElementById("editAdmixtureAdmix1Kg").value = data.admixture_admix1_kg;
      document.getElementById("editAdmixtureAdmix2Kg").value = data.admixture_admix2_kg;
      document.getElementById("editWaterKg").value = data.water_kg;
      document.getElementById("editOrderQuantity").value = data.order_quantity_m3;

      new bootstrap.Modal(document.getElementById("editOrderModal")).show();
    } else {
      alert("Failed to load order details.");
    }
  };

  xhr.onerror = function () {
    alert("Error loading order.");
  };

  xhr.send();
}

// Function to submit Edit Order Form
function submitEditOrderForm() {
    var formData = new FormData(document.getElementById("editOrderForm"));
    formData.append("action", "edit");

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

    xhr.onload = function () {
        alert(xhr.responseText);
        document.getElementById("editOrderModal").classList.remove("show");
        location.reload();
    };

    xhr.onerror = function () {
        alert("Error updating order. Please check your network.");
    };

    xhr.send(formData);
}

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

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

        xhr.onload = function () {
            alert(xhr.responseText);
            location.reload();
        };

        xhr.onerror = function () {
            alert("Error deleting order. Please check your network.");
        };

        xhr.send(formData);
    }
}

function viewOrder(id) {
  fetch("order_actions.php?action=view&id=" + id)
    .then(res => res.json())
    .then(data => {
      if (data.error) {
        alert("Order not found.");
        return;
      }

      document.getElementById("viewOrderNo").innerText = data.order_no;
      document.getElementById("viewOrderDate").innerText = data.order_date;
      document.getElementById("viewCustomerName").innerText = data.customer_name;
      document.getElementById("viewMarketingPerson").innerText = data.marketing_name;
      document.getElementById("viewExecutionDate").innerText = data.execution_date;
      document.getElementById("viewSiteName").innerText = data.site_name;

      document.getElementById("viewAggregate12mKg").innerText = data.aggregate_12m_kg;
      document.getElementById("viewAggregateSandKg").innerText = data.aggregate_sand_kg;
      document.getElementById("viewAggregate20mm1Kg").innerText = data.aggregate_20mm_1_kg;
      document.getElementById("viewAggregate20mm2Kg").innerText = data.aggregate_20mm_2_kg;

      document.getElementById("viewCementCEM1Kg").innerText = data.cement_cem1_kg;
      document.getElementById("viewCementCEM2Kg").innerText = data.cement_cem2_kg;
      document.getElementById("viewAdmixtureAdmix1Kg").innerText = data.admixture_admix1_kg;
      document.getElementById("viewAdmixtureAdmix2Kg").innerText = data.admixture_admix2_kg;
      document.getElementById("viewWaterKg").innerText = data.water_kg;
      document.getElementById("viewOrderQuantity").innerText = data.order_quantity_m3;

      new bootstrap.Modal(document.getElementById("viewOrderModal")).show();
    })
    .catch(err => {
      alert("Failed to load order details.");
      console.error(err);
    });
}





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

 

  <!-- 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>