<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();

if(!isset($_SESSION["user_id"])){
  header("location:../logout.php");
   exit();
}
$branch_d = $_SESSION['branch'];
require_once "../magic/DataBase.php";
$database = new DataBase();

$conn = $database->getConnection();

require_once "../op/CarHistory.php";

$carHistory = new CarHistory($conn);
?>
<div class="panel panel-primary" id="main_supp">
  <div class="panel-heading clearfix" style="font-size:1.2em;">
    <div class="row" style="padding:4px;">
      <div class="col-md-3" style="float:right;">
        <label class="control-label" style="float:right;font-size: 16px">سيارات الفرع </label>
      </div>
    </div>
    <div class="row" style="padding:4px;">
      <div class="col-md-1" style="float:right;padding:2px;">
      </div>
      <div class="col-md-4" style="float:right;padding:2px;">
        <div class="input-group">
          <span class="input-group-addon" style="font-size: 14px;font-weight:bold;background:transparent;color:black;">حالة السيارة </span>
          <select class="form-control" id="status" name="status">
            <option value="1">استعداد</option>
            <?php
            $sql = $conn->prepare("SELECT status_id , status from carstatus where status_id between 2 AND 5 ");
            $sql->execute();
            if ($sql->rowCount() > 0) {
              while ($row = $sql->fetch()) {
                $id = $row["status_id"];
                $val  = $row["status"];
                echo "<option value='$id' >$val</option>";
              }
            } ?>?>
          </select>
          <span class="input-group-btn">
            <button id="status_a" type="button" class="btn btn-primary btn-xs action "><i class="fa fa-search" style="font-size: 22px;font-weight:bold;color:#ff9966; padding:3px; margin:0px;" aria-hidden="true"></i></button>
          </span>
        </div><!-- /input-group -->
      </div>
      <div class="col-md-3" style="float:right;padding:2px;">
        <div class="input-group">
          <span class="input-group-addon" style="font-size: 14px;font-weight:bold;background:transparent;color:black;">طراز</span>
          <select class="form-control" id="kind" name="kind">
            <option value="*">جميع الأنواع</option>
            <?php
            $sql3 = $conn->prepare("SELECT DISTINCT kind from cars where branch = ?");
            $sql3->bindParam(1, $branch_d);
            $sql3->execute();
            if ($sql3->rowCount() > 0) {
              while ($row = $sql3->fetch()) {
                $id = $row["kind"];
                echo "<option value='$id' >$id</option>";
              }
            } ?>
          </select>
          <span class="input-group-btn">
            <button id="kind_a" type="button" class="btn btn-primary btn-xs action "><i class="fa fa-search" style="font-size: 22px;font-weight:bold;color:#ff9966; padding:3px; margin:0px;" aria-hidden="true"></i></button>
          </span>
        </div><!-- /input-group -->
      </div>

      <div class="col-md-3" style="float:right;padding:2px;">
        <div class="input-group">
          <span class="input-group-addon" style="font-size: 14px;font-weight:bold;background:transparent;color:black;">موديل</span>
          <select class="form-control" id="model" name="model">
            <option value="*">جميع الموديلات</option>
            <?php
            $sql = $conn->prepare("SELECT DISTINCT model from cars where branch = ?");
            $sql->bindParam(1, $branch_d);
            $sql->execute();
            if ($sql->rowCount() > 0) {
              while ($row = $sql->fetch()) {
                $model = $row["model"];
                echo "<option value= $model >$model</option>";
              }
            } ?>
          </select>
          <span class="input-group-btn">
            <button id="model_a" type="button" class="btn btn-primary btn-xs action "><i class="fa fa-search" style="font-size: 22px;font-weight:bold;color:#ff9966; padding:3px; margin:0px;" aria-hidden="true"></i></button>
          </span>
        </div><!-- /input-group -->
      </div>
    </div>
  </div>
  <div class="panel-body" style="background-color:#00324d;color:#cce5ff;">
    <div class="table-responsive">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <th class="text-center" width="4%">م</th>
            <th class="text-center" width="15%">حركة</th>
            <th class="text-center" width="4%">أيام</th>
            <th class="text-center" width="8%">طراز</th>
            <th class="text-center" width="7%">لوحة</th>
            <th class="text-center" width="5%">موديل</th>
            <th class="text-center" width="7%">اللون</th>
            <th class="text-center" width="7%">الموقع</th>
            <th class="text-center" width="9%">نهاية التأمين</th>
            <th class="text-center" width="9%">نهاية الترخيص</th>
            <th class="text-center" width="9%">كارت التشغيل</th>
            <th class="text-center" width="12%">الصيانة</th>
          </tr>
        </thead>
        <tbody id="myData">
          <?php
          $output = '';
          $valed = "text-decoration:none;color:#B6F5AC;";
          $v2 = " background-color:rgba(0,0,0,0.55);";
          $expire = "text-decoration:none;color:#AA0202;";
          $x2 = "background-color:#F0F7E4;";
          $sql = $conn->prepare("SELECT naql.carid, cars.branch, cars.kind,cars.color, concat(cars.letters ,' ',cars.numbers) as numbers, cars.model,cars.lic_photo ,cars.lic_expire, cars.carstatus , naql.insurance_expire, 
                              naql.insurance_lic,naql.operationCard, naql.pre_check ,naql.operation_expire ,naql.pre_expire ,branches.b_name
                      from cars , naql ,branches
                      where cars.carid = naql.carid 
                          AND cars.branch = branches.branchID
                          AND cars.carstatus = 1 AND cars.car_job_id = 1
                          AND cars.branch = ? order by carstatus  ");
          $sql->bindParam(1, $branch_d);
          $sql->execute();
          if ($sql->rowCount() > 0) {
            $nn = 0;
            $qty1 = 0;
            $qty2 = 0;
            $qty3 = 0;
            $qty4 = 0;
            $date6 = new DateTime(date("Y-m-d"));
            while ($row = $sql->fetch()) {
               $style="";
              $nn++;
              $output .="<tr><td>$nn</td>";
              $carid = $row['carid'];
              $qty   = $carHistory->car_state($carid);

              $date1 = new DateTime(($row['insurance_expire'])?? 'now');
              $date2 = new DateTime(($row['lic_expire'])?? 'now');
              $date3 = $row['operation_expire'];
              $branch = $row['branch'];
                      if($branch != $branch_d)
                        {
                          $style="color:#DA2D07; background-color:#F0F7E4;font-weight:bold;";
                        }

              if (!empty($date3)) {
                $date3 = new DateTime($date3);
                $qty3  = $date6->diff($date3)->format("%a");
              } else {
                $date3 = "";
              }
              // $date4 = new DateTime($row['pre_expire']);
              $qty1 = $date6->diff($date1)->format("%a");
              $qty2 = $date6->diff($date2)->format("%a");
              // $qty4 = $date6->diff($date4)->format("%a");
              if (($qty1 < 8) || ($date1 < $date6)) {
                $style1 = $expire;
                $back1 = $x2;
              } else {
                $style1 = $valed;
                $back1 = $v2;
              }
              if (($qty2 < 8) || ($date2 < $date6)) {
                $style2 = $expire;
                $back2 = $x2;
              } else {
                $style2 = $valed;
                $back2 = $v2;
              }
              if (($qty3 < 8) || ($date3 < $date6)) {
                $style3 = $expire;
                $back3 = $x2;
              } else {
                $style3 = $valed;
                $back3 = $v2;
              }
              //  if(($qty4 < 8)||($date4 < $date6)){ $style4 = $expire ; $back4 = $x2 ; }else{ $style4 = $valed ; $back4 = $v2 ; }

              $koki = 0;


              $stat = $row['carstatus'];
              if ($stat == 2) {
                $comy = $conn->prepare("SELECT contract_id  from contracts WHERE cont_status = 1 and carid = ? limit 1 ");
                $comy->bindParam(1, $carid);
                $comy->execute();
                if ($comy->rowCount() > 0) {
                  $do = $comy->fetch(PDO::FETCH_ASSOC);
                  $koki      = $do["contract_id"];
                }
                $output .= '<td>
              <a href="rent/cont2close.php?id=' . $koki . '"target="_blank"><button type="button" style="font-weight:bold;font-size:13px;color:black;" class="btn btn-info btn-block btn-xs ">سند قبض</button></a>';
              } else if ($stat == 1) {
                $output .= '<td>
             <a href="rent/newContract.php?carid=' . $carid . '"target="_blank"><button type="button" style="font-weight:bold;font-size:14px;color:black;padding:5px;" class="btn btn-success btn-xs ">عقد أسبوعي</button></a>
            <a href="rent/monthlyContract.php?carid=' . $carid . '"target="_blank"><button type="button" style="font-weight:bold;font-size:14px;color:black;padding:5px;" class="btn btn-danger btn-xs ">شهري</button></a>';
              } else if ($stat > 2) {
                $output .= '<td>
             <a href="#"<button type="button" st="1"  mycar=' . $carid . ' class="btn btn-danger btn-block btn-xs car_ment " style="font-weight:bold;font-size:13px;color:black;">إستعداد</button></a>';
              }

              $output .= '</td>
                      <td >' . $qty . '</td>
                      <td class="text-center">' . $row['kind'] . '</td>
                      <td>' . $row['numbers'] . '</td>
                      <td>' . $row['model'] . '</td>
                      <td>' . $row['color'] . '</td>
                      <td style="'.$style.'">' . $row['b_name'] . '</td>
                      <td class="text-center" style="' . $back1 . '" ><a href="naql/insurance_print.php?J=' . $row['insurance_lic'] . '"target="_blank" style="' . $style1 . '" >' . $row['insurance_expire'] . '</a></td>
                      <td class="text-center" style="' . $back2 . '" ><a href="naql/lic_print.php?J=' . $carid . '"target="_blank" style="' . $style2 . '">' . $row['lic_expire'] . '</a></td>
                      <td class="text-center" style="' . $back3 . '"><a href="naql/operation_print.php?J=' . $row['operationCard'] . '"target="_blank" style="' . $style3 . '">' . $row['operation_expire'] . '</a></td>
                      <td>
                       <a href="a/ment_b_r.php?id=' . $carid . ' "target="_blank"><button style="font-weight:bold;font-size:13px;color:black;" class="btn btn-danger btn-m ">صيانة</button></a>
                       <a href="ment/car_ment_br.php?id=' . $carid . ' "target="_blank"><button style="font-size:11px;color:#E5FDCD;" class="btn btn-success btn-m ">ص</button></a>
                       <a href="rent/car_contracts.php?dd=' . $carid . ' "target="_blank"><button style="font-size:11px;color:#620316;" class="btn btn-info btn-m ">ع</button></a>
                      </td>
                    </tr>';
            }
          } else {
            $output .= '<tr><td colspan="10">لا يوجد سجلات ...</td></tr>';
          }
          echo $output;
          ?>
        </tbody>
        <tfoot></tfoot>
      </table>
    </div>
  </div>
</div>
<!-- panel body style -->
<script>
  $(document).ready(function() {
   $(".action").click(function() {
        const filters = {
            branch: "<?= $branch_d ?>",
            status: $("#status").val(),
            kind: $("#kind").val(),
            model: $("#model").val()
        };

        $.ajax({
            url: "actions/branch13cars.php",
            method: "POST",
            data: filters,
            success: function(data) {
                $("#myData").html(data);
            },
            error: function(xhr) {
                console.error("Error:", xhr.statusText);
            }
        });
    });

 // Car status change
    $(document).on('click', '.car_ment', function(e) {
        e.preventDefault();
        // const carid = $(this).data('carid');
         const st = $(this).attr("st");
        const carid = $(this).attr("mycar");
        $.ajax({
            url: "actions/day_action.php",
            method: "POST",
            data: { 
                st: 1, 
                carid: carid 
            },
            success: function() {
                $('#site').load("includes/branchCars.php");
            },
            error: function(xhr) {
                console.error("Error:", xhr.statusText);
            }
        });
    });//end car status

  });
</script>
