<?php
require_once "../magic/session_config.php";
bdr_start_session();
$branch = $_SESSION['branch'];
include "../actions/dbPDO.php";
include "../op/aksat_wanted.php";
$today = date("Y-m-d");
?>
<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: 15px">متابعة التشغيل</label>
      </div>
      <div class="col-md-2" style="float:left;">
        <a href="aksat/aksat_wanted.php" target="_blank"><button type="button" style="float:right;  margin-right:8px; color: #000 ;" class="btn btn-danger">مستحق السداد</button></a>
      </div>
      <div class="col-md-2" style="float:left;">
        <a href="aksat/aksat_all.php" target="_blank"><button type="button" style="float:right;  margin-right:8px; color: #000 ;" class="btn btn-success">حصر المقسطين</button></a>
      </div>
      <div class="col-md-2" style="float:left;">
        <input type="text" id="nn" name="nn" class="form-control" name="nn" style="float:left; margin-right:8px; color: #000 ;" placeholder="ابحث بالرقم">
      </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="8%">رقم العقد</th>
            <th class="text-center" width="25%">الإسم</th>
            <th class="text-center" width="7%">متأخرات</th>
            <th class="text-center" width="10%">الجوال</th>
            <th class="text-center" width="9%">استحقاق</th>
            <th class="text-center" width="8%">طراز</th>
            <th class="text-center" width="5%">رقم</th>
            <th class="text-center" width="4%">موديل</th>
            <th class="text-center" width="9%">أخر سداد</th>
            <th class="text-center" width="5%">تأخير</th>
            <th class="text-center" width="10%">التفويض</th>
          </tr>
        </thead>
        <tbody id="myData">
          <?php
          $output = '';
          $sql = $db->prepare("SELECT customers.cust_name ,customers.phone,cars.kind , cars.numbers , cars.model , aksat_contract.day_cost , aksat_contract.tamm_expire ,
                               aksat_contract.contract_id , aksat_contract.start , aksat_contract.kest , aksat_contract.tash
                              from customers , aksat_contract , cars
                              WHERE aksat_contract.cust_id = customers.cust_id AND aksat_contract.carid = cars.carid
                              AND aksat_contract.status = 3 AND aksat_contract.branch = ? order by aksat_contract.contract_id ");
          $sql->bindParam(1, $branch);
          $sql->execute();
          if ($sql->rowCount() > 0) {
            while ($row = $sql->fetch()) {
              $ss = $row['contract_id'];
              $tash = $row['tash'];
              $wk = next_tash($ss);
              $tot_debt    = $wk["tot_debt"];
              $tot_payed   = $wk["tot_payed"];
              $tot_wanted  = $wk["tot_wanted"];
              $late        = $wk["late"];
              $next_wanted = $wk["next_wanted"];
              $next_start   = $wk["next_start"];
              $last_pay    = $wk["last_pay"];

              $date1 = new DateTime($row['tamm_expire']);
              $date2 = new DateTime(date("Y-m-d"));
              $qty = $date2->diff($date1)->format("%a");

              if ($late > 0) {
                $style = 'style="color:#DA2D07; background-color:#F9F5F5;font-weight:bold;"';
                if ($late > 30) {
                  $tash2 = $db->prepare("SELECT max(start) as start from tash_in where contract_id = ?");
                  $tash2->bindParam(1, $ss);
                  $tash2->execute();
                  if ($tash2->rowCount() > 0) {
                    $ak = $tash2->fetch(PDO::FETCH_ASSOC);
                    $last_start = $ak['start'];
                    if ($last_start < $today) {
                      $date1 = new DateTime($last_start);
                      $date2 = new DateTime($today);
                      $last_late = $date2->diff($date1)->format("%a");
                      if ($last_late > 30) {
                        $maxsql = $db->prepare("SELECT max(tash_id) as maxd FROM tash_in");
                        $maxsql->execute();
                        if ($maxsql->rowCount() > 0) {
                          $dow = $maxsql->fetch(PDO::FETCH_ASSOC);
                          $maxD = $dow['maxd'] + 1;
                        }
                        $last_start = date('Y-m-d', strtotime($last_start . ' + 1 month'));
                        $endd = date('Y-m-d', strtotime($last_start . ' - 1 days'));
                        $endd  = date('Y-m-d', strtotime($endd . ' + 1 month'));
                        $new_tash = $db->prepare("INSERT INTO tash_in(tash_id, contract_id, wanted, start, endd)
                                        values(?,?,?,?,?)");
                        $new_tash->bindParam(1, $maxD);
                        $new_tash->bindParam(2, $ss);
                        $new_tash->bindParam(3, $tash);
                        $new_tash->bindParam(4, $last_start);
                        $new_tash->bindParam(5, $endd);
                        $new_tash->execute();
                      }
                    }
                  }
                }
              } else {
                $style = '';
                $tot_debt = $next_wanted;
                $date1 = new DateTime($next_start);
                $date2 = new DateTime($today);
                $late = $date2->diff($date1)->format("%a");
              }
              $output .= '<tr><td>
                           <a href="aksat/tash2pay.php?id=' . $ss . '"target="_blank"><button type="button" style="font-weight:bold ; font-size:14px; padding:2;" class="btn btn-danger btn-xs btn-block ">' . $ss . '</button></a>
                           </td>
                           <td>' . $row['cust_name'] . '</td>
                           <td ' . $style . '>' . $tot_debt . '</td>
                           <td>' . $row['phone'] . '</td>
                           <td ' . $style . '>' . $next_start . '</td>
                           <td class="text-center" >' . $row['kind'] . '</td>
                           <td class="text-center" >' . $row['numbers'] . '</td>
                           <td class="text-center" >' . $row['model'] . '</td>
                           <td class="text-center" >' . $last_pay . '</td>
                           <td class="text-center" ' . $style . ' >' . $late . '</td>';
              if (($qty < 8) || ($date1 < $date2)) {
                $output .= '    <td class="text-center" style="color:#DA2D07;background-color:#F0F7E4;" >' . $row['tamm_expire'] . '</td>   </tr>';
              } else {
                $output .= '    <td class="text-center">' . $row['tamm_expire'] . '</td>  </tr>';
              }
            }
          } else {
            $output .= '<tr><td colspan="11">لا يوجد سجلات ...</td></tr>';
          }
          echo $output;
          ?>
        </tbody>
        <tfoot></tfoot>
      </table>
    </div>
  </div>
</div>
<?php
$outcont = array();
$cont_sr = $db->prepare("SELECT contract_id , concat(contract_id,' ', numbers) as ko  from active where branch = ? AND cont_status = 1");
$cont_sr->bindParam(1, $branch);
$cont_sr->execute();
$i = 0;
if ($cont_sr->rowCount() > 0) {
  while ($row = $cont_sr->fetch()) {
    $outcont[$i] = array(
      "value" => $row["ko"],
      "data" => $row["contract_id"]
    );
    $i++;
  }
} else {
  $outcont[0] = 'لا يوجد ';
}
?>
<script>
  $(document).ready(function() {

    var arr = JSON.parse('<?php echo json_encode($outcont); ?>');
    $('#nn').autocomplete({
      lookup: arr,
      maxHeight: 200,
      onSelect: function(suggestion) {
        $('#nn_sr').attr("href", "rent/cont2close.php?id= " + suggestion.data);
      },
    });

    $("#ad_a").click(function(event) {
      event.preventDefault();
      var ad_a = $("#ad").val();
      $.ajax({
        url: "rent/action_flow.php",
        method: "POST",
        data: {
          ad_a: ad_a
        },
        success: function(data) {
          $("#myData").html(data);
        },
        error: function(result) {
          alert(result.statusText);
        }
      });
    });

    $("#namm_a").click(function(event) {
      event.preventDefault();
      var name = $("#namm").val();
      $.ajax({
        url: "rent/action_flow.php",
        method: "POST",
        data: {
          name: name
        },
        success: function(data) {
          $("#myData").html(data);
        },
        error: function(result) {
          alert(result.statusText);
        }
      });
    });
    $("#numb_a").click(function(event) {
      event.preventDefault();
      var numb = $("#numb").val();
      $.ajax({
        url: "rent/action_flow.php",
        method: "POST",
        data: {
          numb: numb
        },
        success: function(data) {
          $("#myData").html(data);
        },
        error: function(result) {
          alert(result.statusText);
        }
      });
    });

    $("#datt_a").click(function(event) {
      event.preventDefault();
      var datt = $("#datt").val();
      if (datt.length = 0) {
        var d = new Date();
      }
      $.ajax({
        url: "rent/action_flow.php",
        method: "POST",
        data: {
          datt: datt
        },
        success: function(data) {
          $("#myData").html(data);
        },
        error: function(result) {
          alert(result.statusText);
        }
      });
    });
  });
</script>