<?php 
ob_start();
include("configa.php");
session_start();


if( isset($_GET['track_number'])  ){
  $track_number = $_GET['track_number'];
 
}else{
  $track_number = 1; //এই কোড $id = 1; না দিলে; যদি সরাসরি view.php হিট করে; তাহলে Error দেখাবেন//
  }




function convertToYMD($date) {
    $parts = explode('/', $date);
    if (count($parts) == 3) {
        return $parts[2] . '-' . $parts[1] . '-' . $parts[0];
    }
    return '';
}

$truck           = $_POST['truck'] ?? '';
$start_date      = !empty($_POST['start_date']) ? convertToYMD($_POST['start_date']) : '';
$end_date        = !empty($_POST['end_date']) ? convertToYMD($_POST['end_date']) : '';
$confirmNon      = $_POST['confirmNon'] ?? '';
$orderReady      = $_POST['orderReady'] ?? '';
$currierDeliverd = $_POST['currierDeliverd'] ?? '';
$currierName     = $_POST['currierName'] ?? '';
$delivery        = $_POST['delivery'] ?? '';
$editor          = $_POST['editor'] ?? '';

// =================== Default query ===================
// যদি সব ফিল্ড খালি থাকে, আজকের দিন অনুযায়ী রেকর্ড দেখাবে
if( empty($truck) && empty($confirmNon) && empty($orderReady) && empty($currierDeliverd) && empty($currierName) && empty($delivery) && empty($editor) && empty($start_date) && empty($end_date) ) {
    $today = date('Y-m-d');
    $sql = "SELECT * FROM final_order_summary WHERE DATE(submit_date) = '$today'";
} else {
    // Dynamic condition build
    $sql = "SELECT * FROM final_order_summary WHERE 1=1";

    if( !empty($truck) ){ 
        $sql .= " AND track_number = '$truck'"; 
    }
    if( !empty($confirmNon) ){ 
        $sql .= " AND confirm = '$confirmNon'"; 
    }
    if( !empty($orderReady) ){ 
        $sql .= " AND orderReady = '$orderReady'"; 
    }
    if( !empty($currierDeliverd) ){ 
        $sql .= " AND currierDeliverd = '$currierDeliverd'"; 
    }
    if( !empty($currierName) ){ 
        $sql .= " AND currierName = '$currierName'"; 
    }
    if( !empty($delivery) ){ 
        $sql .= " AND delivery = '$delivery'"; 
    }
    if( !empty($editor) ){ 
        $sql .= " AND editor = '$editor'"; 
    }
    if( !empty($start_date) && !empty($end_date) ){ 
        $sql .= " AND submit_date BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59.999999'"; 
    }
}

$for_track_number = mysqli_query($conn, "SELECT * FROM final_order_summary WHERE track_number = '$track_number'") or die(mysqli_error($conn));
$row_track_number = mysqli_fetch_object($for_track_number); 
?>



<style type="text/css">

*{
font-family: sutonnyOMJ, Arial;
}

.catagory_display_container{
  width: 100%; 
  margin-left: auto; 
  margin-right: auto;  
  background-color:#eef6f9;
  /*background-color: red;*/
  display: flex;
  flex-direction: column;
}

table, tr, th, td{
  width: 100%;
  font-family: sutonnyOMJ;
}


 /* পুরো টেবিলের জন্য স্টাইল */
table {
  width: 100%;
  border-collapse: collapse; /* বর্ডারগুলোকে একসাথে মিশিয়ে দেয় */
  font-family: Arial, sans-serif;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden; /* বর্ডার-রেডিয়াস ঠিকঠাক কাজ করার জন্য */
  position: relative;
}

/* টেবিল হেডারের জন্য স্টাইল */
th {
  background-color: #4CAF50; /* গাঢ় সবুজ রঙ */
  color: white;
  padding: 12px 15px;
  text-align: left;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* টেবিলের সাধারণ ডেটা সেলের জন্য স্টাইল */
td {
  padding: 12px 15px;
  border-bottom: 1px solid #ddd; /* হালকা ধূসর বর্ডার */
  position: relative; /* টুলটিপ (tooltip) এর জন্য */
}

/* জোড় ও বিজোড় সারির জন্য আলাদা রঙ */
tr:nth-child(even) {
  background-color: #f2f2f2;
}

/* মাউস হোভার করার সময় সারির রঙ পরিবর্তন */
tr:hover {
  background-color: #ddd;
  transition: background-color 0.3s ease;
}

/* ছবির জন্য স্টাইল */
td img {
  border-radius: 4px;
  object-fit: cover; /* ছবির আকার ঠিক রাখতে */
  width: 1in;
  height: 1in;
  transition: transform 0.3s ease;
}

td img:hover {
  transform: scale(1.1); /* হোভার করলে ছবি একটু বড় হবে */
}

/* ড্রপডাউন সিলেক্ট বক্সের জন্য স্টাইল */
td select {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: white;
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
}

td select:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
}

/* টুলের জন্য স্টাইল (যেটা th-এর উপরে দেখাবে) */
.tooltip {
  visibility: hidden;
  background-color: #333;
  color: #fff;
  text-align: center;
  border-radius: 4px;
  padding: 5px 10px;
  position: absolute;
  z-index: 10;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s ease;
  white-space: nowrap;
}

td:hover .tooltip {
  visibility: visible;
  opacity: 1;
}

.sl{
  width: 30pt;
}

.nameAddress{
  width: 2in;
}


table {
    /* উপরের টেবিলে style অ্যাট্রিবিউট ব্যবহার না করে এখানে ক্লাস ব্যবহার করা ভালো */
    width: 100%; 
    table-layout: fixed;
    border-collapse: collapse; /* বর্ডারগুলোকে সুন্দরভাবে একত্রিত করার জন্য */
}
td {
    border: 1px solid #ccc; /* বোঝার সুবিধার জন্য বর্ডার যোগ করা হয়েছে */
}

textarea{
  width: 100%;
}


.searcBox{
  padding: 30pt;
  width: 70%;
  height: 10%;
  background-color: white;
  position: relative;
  left: 30%;
  transform: translate(-20%);
  box-sizing: border-box;
}

option[disabled][selected] {
  color: #a0a0a0; /* একটি হালকা ধূসর রং */
}

input, select{
  width: 32%;
  height: 30pt;
}

.search{
  width: 100%;
  cursor: pointer;
}
</style>




<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', () => {
  const selects = document.querySelectorAll('select');

  selects.forEach(select => {
    select.addEventListener('change', (event) => {
      const row = event.target.closest('tr'); // পুরো সারিটি খুঁজে বের করে
      const status = event.target.value;

      // ক্লাসের নাম যোগ ও বিয়োগ করে রঙ পরিবর্তন
      if (status === 'confirm') {
        row.classList.add('confirmed');
        row.classList.remove('non-confirmed');
      } else if (status === 'non confirm') {
        row.classList.add('non-confirmed');
        row.classList.remove('confirmed');
      } else {
        row.classList.remove('confirmed', 'non-confirmed');
      }
    });
  });
});
</script>

  <div class="catagory_display_container">




<script>
document.addEventListener('DOMContentLoaded', () => {
    const table = document.querySelector('table');
    const headers = Array.from(table.querySelectorAll('th'));
    const rows = table.querySelectorAll('tr:not(:first-child)');

    rows.forEach(row => {
        const cells = Array.from(row.querySelectorAll('td'));
        cells.forEach((cell, index) => {
            const headerText = headers[index].innerText;
            if (headerText) {
                const tooltip = document.createElement('span');
                tooltip.classList.add('tooltip');
                tooltip.innerText = headerText;
                cell.appendChild(tooltip);
            }
        });
    });
});
</script>


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<!-- Flatpickr JS -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>



<div class="searcBox">

<?php 
$for_address = mysqli_query($conn, "SELECT * FROM final_order_customer WHERE mobile = '$row_track_number->mobile'") or die(mysqli_error($conn));
$row_address = mysqli_fetch_object($for_address); 
// তারিখ
echo isset($row_address->sumit_date) ? $row_address->sumit_date : '';
echo "<br>";
// নাম
$full_name = '';
if (isset($row_address->first_name)) $full_name .= $row_address->first_name . ' ';
if (isset($row_address->last_name)) $full_name .= $row_address->last_name;
echo trim($full_name);
echo "<br>";
// ঠিকানা
$address = '';
if (isset($row_address->address)) $address .= $row_address->address . ', ';
if (isset($row_address->up)) $address .= $row_address->up . ', ';
if (isset($row_address->upazila)) $address .= $row_address->upazila . ', ';
if (isset($row_address->district)) $address .= $row_address->district . ', ';
if (isset($row_address->division)) $address .= $row_address->division;
echo rtrim($address, ', ');
echo "<br>";
// মোবাইল
echo isset($row_address->mobile) ? $row_address->mobile : '';
?>

</div>



<table>
  <tr>
    <th class="sl">sl</th>
    <th>পণ্যের বিবরণ ও ছবি</th>
    <th>পণ্যের নাম</th>
    <th>আইটেম</th>
    <th>পার্সোন</th>
    <th>সিরিয়াল</th>
    <th>বিক্রেতা</th>
    <th>মুল্য</th>
    <th>ডিসকাউন্ট</th>
    <th>বর্তমান মুল্য</th>
    <th>সাইজ</th>
    <th>ওজন</th>
    <th>কোয়ান্টিটি</th>
    <th>ডিসকাউন্ট কোড</th>
    <th>বর্তমান ডিসকাউন্ট</th>

  </tr>



<?php  
$for_items = mysqli_query($conn, "SELECT * FROM final_order_item WHERE track_number = '$track_number'") or die(mysqli_error($conn));
$i = 1; 
while ($row_item = mysqli_fetch_object($for_items)) { ?>
<tr>
  <td class="sl"><input type="text" name="sl[]" value="<?php echo $i++; ?>"></td>
  <td class="sl">
    <img src="category/<?php echo $row_item->category_picture;?>" width="50">
    <input type="hidden" name="category_picture[]" value="<?php echo $row_item->category_picture;?>">
  </td>
  <td><input type="text" name="product_name[]" value="<?php echo $row_item->product_name;?>"></td>
  <td><input type="text" name="item[]" value="<?php echo $row_item->item;?>"></td>
  <td><input type="text" name="person[]" value="<?php echo $row_item->person;?>"></td>
  <td><input type="text" name="gks[]" value="<?php echo $row_item->gks;?>"></td>
  <td><input type="text" name="seller[]" value="<?php echo $row_item->seller;?>"></td>
  <td><input type="text" name="price[]" value="<?php echo $row_item->price;?>"></td>
  <td><input type="text" name="discount[]" value="<?php echo $row_item->discount;?>"></td>
  <td><input type="text" name="current_price[]" value="<?php echo $row_item->current_price;?>"></td>
  <td><input type="text" name="size[]" value="<?php echo $row_item->size;?>"></td>
  <td><input type="text" name="weight[]" value="<?php echo $row_item->weight;?>"></td>
  <td><input type="text" name="quantity[]" value="<?php echo $row_item->quantity;?>"></td>
  <td><input type="text" name="discount_code[]" value="<?php echo $row_item->discount_code;?>"></td>
  <td><input type="text" name="discount_special[]" value="<?php echo $row_item->discount_special;?>"></td>
</tr>
<?php } ?>


</table>




<table>
  <tr>
  <th>মোট</th>
  <th>ভাড়া</th>
  <th>সর্বমোট</th>
  </tr>
<?php  
$for_summary = mysqli_query($conn, "SELECT * FROM final_order_summary WHERE track_number = '$track_number'") or die(mysqli_error($conn));
$row_summary = mysqli_fetch_object($for_summary);  
?>
<tr>
  <td><input type="text" name="total" value="<?php echo $row_summary->total;?>"></td>
  <td><input type="text" name="delivery_charge" value="<?php echo $row_summary->delivery_charge;?>"></td>
  <td><input type="text" name="grand_total" value="<?php echo $row_summary->grand_total;?>"></td>
  <td></td>
</tr>
</table>


<style type="text/css">
  input{
    width: 100%;
    text-align: center;
  }
</style>


<script>
document.addEventListener("DOMContentLoaded", function() {
    function calculateTotal() {
        let quantities = document.querySelectorAll("input[name='quantity[]']");
        let prices = document.querySelectorAll("input[name='current_price[]']");
        let totalField = document.querySelector("input[name='total']");

        let total = 0;
        quantities.forEach((q, i) => {
            let qty = parseFloat(q.value) || 0;
            let price = parseFloat(prices[i].value) || 0;
            total += qty * price;
        });

        totalField.value = total.toFixed(2); // দশমিক সহ দেখাবে
    }

    // প্রথমবার লোড হলে হিসাব করুক
    calculateTotal();

    // quantity বা current_price পরিবর্তন হলে আবার হিসাব করবে
    document.querySelectorAll("input[name='quantity[]'], input[name='current_price[]']").forEach(input => {
        input.addEventListener("input", calculateTotal);
    });
});
</script>


<script>
document.addEventListener("DOMContentLoaded", function() {
    function calculateCharges() {
        let quantities = document.querySelectorAll("input[name='quantity[]']");
        let weights = document.querySelectorAll("input[name='weight[]']");
        let prices = document.querySelectorAll("input[name='current_price[]']");
        
        let totalField = document.querySelector("input[name='total']");
        let deliveryField = document.querySelector("input[name='delivery_charge']");
        let grandTotalField = document.querySelector("input[name='grand_total']");

        let total = 0;
        let deliveryCharge = 0;

        quantities.forEach((q, i) => {
            let qty = parseFloat(q.value) || 0;
            let price = parseFloat(prices[i].value) || 0;
            let weight = parseFloat(weights[i].value) || 0;

            // ----- Product Price Calculation -----
            total += qty * price;

            // ----- Delivery Charge Calculation -----
            let totalWeight = qty * weight; // মোট ওজন
            if (totalWeight > 0) {
                if (totalWeight <= 0.5) {
                    deliveryCharge += 120;
                } else if (totalWeight <= 1) {
                    deliveryCharge += 130;
                } else {
                    // ১ কেজির বেশি হলে
                    deliveryCharge += 130 + Math.ceil(totalWeight - 1) * 20;
                }
            }
        });

        totalField.value = total.toFixed(2);
        deliveryField.value = deliveryCharge.toFixed(2);
        grandTotalField.value = (total + deliveryCharge).toFixed(2);
    }

    // প্রথমবার লোড হলে হিসাব করবে
    calculateCharges();

    // quantity, weight, current_price পরিবর্তন হলে আবার হিসাব করবে
    document.querySelectorAll("input[name='quantity[]'], input[name='weight[]'], input[name='current_price[]']").forEach(input => {
        input.addEventListener("input", calculateCharges);
    });
});
</script>



</div>



<?php
// End capturing the output and store it in a variable
$catagory_display_content = ob_get_clean();

// Now include frameForAll.php, which will use $catagory_display_content
include("frameForAll.php");

// mysqli_close($conn); // You might want to close the connection after all database operations
ob_end_flush();
?>



<!DOCTYPE html>
<html>
<head>

  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<meta name="theme-color" content="#FF0000">
    
<title>অনলাইন শপ</title>
    

  
</head>
<body>


<style type="text/css">




</style>

<!----------------------------->
<script>
  flatpickr("#start_date", {
    dateFormat: "d/m/Y", // DD/MM/YYYY format
    position: "below"     // Force show calendar below
  });

  flatpickr("#end_date", {
    dateFormat: "d/m/Y",
    position: "below"
  });
</script>

<!-- ------------------------- -->
  

</body>
</html>