<?php

include "../actions/dbPDO.php";
$sql = $db->prepare("SELECT contract_id ,date_in from contracts where cont_status = 2 and close_at IS NULL LIMIT 500");
$sql->execute();
if($sql->rowCount()>0)
{
   while($row = $sql->fetch())
    {    $contract_id = $row["contract_id"];$date_in = $row["date_in"];
    $insql  = $db->prepare("SELECT max(sanad_date) as maxin from invoice where contract_id = ?");
    $insql->bindParam(1,$contract_id);
    $insql->execute();
    if($insql->rowCount()>0){$max = $insql->fetch(PDO::FETCH_ASSOC);
        $maxin 		= $max["maxin"];
    $outsql = $db->prepare("SELECT max(sanad_out) as maxout from outvoice where contract_id = ?");
    $outsql->bindParam(1,$contract_id);
    $outsql->execute();
  if($outsql->rowCount()>0){$mat = $outsql->fetch(PDO::FETCH_ASSOC);
        $maxout 		= $mat["maxout"];
    if ($maxout > $maxin){ $mxx = $maxout ;}else{ $mxx = $maxin ;}
    if (empty($maxout)){ $mxx = $maxin ;}
    if (empty($maxin)){ $mxx = $date_in ;}
      $up1 = $db->prepare("UPDATE contracts set close_at = ?  where contract_id = ?");
      $up1->bindParam(1,$mxx);
      $up1->bindParam(2,$contract_id);
      $up1->execute();
    }
 }
}
}

?>
