<?php
require_once "../magic/session_config.php";
bdr_start_session();
$branch = $_SESSION['branch'];

require_once "../op/wanted.php";
require_once "../magic/DataBase.php";
$database = new DataBase();

$conn = $database->getConnection();
$output = '';
$tot_wanted = 0;
$nn = 0;
$sql = $conn->prepare("SELECT customers.cust_name ,customers.phone,cars.kind , cars.numbers , cars.model , contracts.day_cost , contracts.tamm_expire ,
                 contracts.contract_id , contracts.date_out ,contracts.branch , contracts.open_at ,  contracts.carcheck
                 from customers , contracts , cars
                 WHERE contracts.cust_id = customers.cust_id AND contracts.carid = cars.carid
                  AND contracts.cont_status = 1 AND contracts.branch = ? order by contracts.contract_id");
$sql->bindParam(1, $branch);
$sql->execute();
if ($sql->rowCount() > 0) {
  while ($row = $sql->fetch()) {
    $nn++;
    $contract_id     = $row['contract_id'];
    $wanted       = new  Wanted($conn, $contract_id);
    $pay       = $wanted->wanted();
    $ww        = $pay["wanted"];
    // $days_qty  = $pay["days_qty"] ;
    $late = $pay["late"];
    $payed     = $pay["payed"];

    $open_at   = $row["open_at"];

    $bt_style = "btn-danger";
    if (($open_at != $branch) || $open_at == 5) {
      $bt_style = "btn-info";
    }


    $date1 = new DateTime($row['tamm_expire']);
    $date2 = new DateTime(date("Y-m-d"));
    $qty = $date2->diff($date1)->format("%a");
    $carcheck = $row['carcheck'];
    if ($ww > 1000) {
      $style = 'style="color:#DA2D07; background-color:#F9F5F5;font-weight:bold;"';
    } else if (($ww < 1000) && ($ww > 500)) {
      $style = 'style="color:#420000; background-color:#F6E9CA;font-weight:bold;"';
    } else {
      $style = '';
    }
    $style_late = '';
    if ($late > 40) {
      $style = 'style="color:#DA2D07; background-color:#d0d0d0;font-weight:bold;"';
      $style_late = $style;
    } else if (($late < 40) && ($late > 6)) {
      $style = 'style="color:#420000; background-color:#F6E9CA;font-weight:bold;"';
    } else {
      $style = '';
    }

    if (!empty($carcheck)) {
      $output .= '<tr><td>' . $nn . '</td>';
    } else {
      $output .= '<tr><td style="color:#DA2D07; background-color:#F0F7E4;font-weight:bold;">' . $nn . '</td>';
    }
    $output .= '<td>
                       <a href="rent/cont2close.php?id=' . $contract_id . '"target="_blank"><button type="button" style="font-weight:bold ; font-size:14px; padding:2;" class="btn ' . $bt_style . ' btn-xs btn-block ">' . $contract_id . '</button></a>
                       </td>
                       <td>' . $row['cust_name'] . '</td><td ' . $style . '>' . $ww . '</td>
                                  <td>' . $row['phone'] . '</td>
                                  <td class = "table-info">' . $row['date_out'] . '</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" ' . $style_late . ' >' . $late . '</td>

                                  <td class="text-center" >' . $row['day_cost'] . '</td>
                                  <td class="text-center" >' . $payed . '</td> ';

    if (($qty == 0) || ($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>';
    }
    if ($ww > 0) {
      $tot_wanted += $ww;
    }
  }
} else {
  $output .= '<tr><td colspan="13">لا يوجد سجلات ...</td></tr>';
}

$sql = $conn->prepare("SELECT customers.cust_name ,customers.phone,cars.kind , cars.numbers , cars.model , contracts.day_cost , contracts.tamm_expire ,
            contracts.contract_id , contracts.date_out ,contracts.branch , contracts.open_at
            from customers , contracts , cars
            WHERE contracts.cust_id = customers.cust_id AND contracts.carid = cars.carid
             AND contracts.cont_status = 1 AND contracts.open_at = ? AND contract_id NOT IN (
               SELECT contract_id from contracts where branch = ? AND cont_status = 1)
                 order by contracts.contract_id");
$sql->bindParam(1, $branch);
$sql->bindParam(2, $branch);
$sql->execute();
if ($sql->rowCount() > 0) {
  $nn = 0;
  while ($row = $sql->fetch()) {
    $nn++;
    $contract_id     = $row['contract_id'];
    $wanted       = new  Wanted($conn, $contract_id);
    $pay       = $wanted->wanted();
    $ww        = $pay["wanted"];
    $late      = $pay["late"];
    $payed     = $pay["payed"];

    $date1 = new DateTime($row['tamm_expire']);
    $date2 = new DateTime(date("Y-m-d"));
    $qty = $date2->diff($date1)->format("%a");
    if ($ww > 1000) {
      $style = 'style="color:#DA2D07; background-color:#F9F5F5;font-weight:bold;"';
    } else if (($ww < 1000) && ($ww > 500)) {
      $style = 'style="color:#420000; background-color:#F6E9CA;font-weight:bold;"';
    } else {
      $style = '';
    }
    $output .= '<tr><td>' . $nn . '</td>
                     <td>
                  <button type="button" style="font-weight:bold ; font-size:14px; padding:2;" class="btn btn-info btn-xs btn-block ">' . $contract_id . '</button>
                  </td>
                  <td>' . $row['cust_name'] . '</td><td ' . $style . '>' . $ww . '</td>
                             <td>' . $row['phone'] . '</td>
                             <td class = "table-info">' . $row['date_out'] . '</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" >' . $late . '</td>
                             <td class="text-center" >' . $row['day_cost'] . '</td>
                             <td class="text-center" >' . $payed . '</td> ';

    if (($qty == 0) || ($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>';
    }
    if ($ww > 0) {
      $tot_wanted += $ww;
    }
  }
}
?>
<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">متابعة عقود الفرع المفتوحة <span class="badge"><?php echo $nn; ?></span></label>
      </div>
      <div class="col-md-3" style="float:right;">
        <label class="control-label" style="float:right;font-size: 15px"> إجمالي مستحق <span class="badge"><?php echo $tot_wanted; ?></span></label>
      </div>
      <div class="col-md-2" style="float:left;">
        <a href="rent/cont_flow_print.php?br=<?php echo $branch; ?>" target="_blank"><button type="button" class="btn btn-success btn-sm ">حركة السداد</button></a>
      </div>
      <div class="col-md-2" style="float:left;">
        <a id="nn_sr" href="" 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>
    <form id="update7" method="post" class="form-horizontal" style="float:center;">
      <div class="row" style="padding:4px;">
        <div class="col-md-3" style="float:right;padding:2px;">
          <label for="namm" class="control-label" style="float:right;margin:5px;"> باسم المستاجر <span style="float:right;margin-left:10px;"><button id="namm_a" type="button" class="btn btn-primary btn-xs "><i class="fa fa-search" style="font-size: 14px;font-weight:bold;color:#ff9966;" aria-hidden="true"></i></button></span></label>
          <input type="text" class="form-control" style="float:right;" id="namm" name="namm" placeholder="اسم المستأجر" />
        </div>
        <div class="col-md-2" style="float:right;padding:2px;">
          <label for="numb" class="control-label" style="float:right;margin:5px;">برقم <span style="float:right;margin-left:10px;"><button id="numb_a" type="button" class="btn btn-primary btn-xs "><i class="fa fa-search" style="font-size: 14px;font-weight:bold;color:#ff9966;" aria-hidden="true"></i></button></span></label>
          <input type="number" class="form-control" style="float:right;" id="numb" name="numb" placeholder="الموديل" />
        </div>
        <div class="col-md-2" style="float:right;padding:2px;">
          <label for="datt" class="control-label" style="float:right;margin:5px;">حني تاريخ<span style="float:right;margin-left:10px;"><button id="datt_a" type="button" class="btn btn-primary btn-xs "><i class="fa fa-search" style="font-size: 14px;font-weight:bold;color:#ff9966;" aria-hidden="true"></i></button></span></label>
          <input type="text" class="form-control" style="float:right;" id="datt" name="datt" placeholder="فتح عقد" readonly />
          <script>
            $(function() {
              var calendar = $.calendars.instance('');
              $('#datt').calendarsPicker({
                calendar: calendar
              });
            });
          </script>
        </div>
        <div class="col-md-4" style="float:right;padding:2px;">
          <label for="ad" class="control-label" style="float:right;margin:5px;">نوع السيارة <span style="float:right;margin-left:10px;"><button id="ad_a" type="button" class="btn btn-primary btn-xs "><i class="fa fa-search" style="font-size: 14px;font-weight:bold;color:#ff9966;" aria-hidden="true"></i></button></span></label>
          <input type="text" class="form-control" style="float:right;" id="ad" name="ad" placeholder="جاري التحديث" />
        </div>

      </div>

    </form>
  </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="6%">عقد</th>
            <th class="text-center" width="25%">الإسم</th>
            <th class="text-center" width="6%">متأخرات</th>
            <th class="text-center" width="8%">الجوال</th>
            <th class="text-center" width="10%">فتح العقد</th>
            <th class="text-center" width="7%">طراز</th>
            <th class="text-center" width="5%">رقم</th>
            <th class="text-center" width="4%">موديل</th>
            <th class="text-center" width="4%">تأخير</th>
            <th class="text-center" width="4%">يومي</th>
            <th class="text-center" width="6%">المدفوع</th>
            <th class="text-center" width="10%">التفويض</th>
          </tr>
        </thead>
        <tbody id="myData">
          <?php
          echo $output;
          ?>
        </tbody>
        <tfoot></tfoot>
      </table>
    </div>
  </div>
</div>
<?php
$outcont = array();
$cont_sr = $conn->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>