<?php

require_once "../magic/session_config.php";
bdr_start_session();
ob_start();
$father = $_SESSION["user_id"];
$branch = $_SESSION["branch"];

if (!isset($_SESSION["user_id"])) {
	header("location:../logout.php");
}
include "../actions/dbPDO.php";
if (isset($_POST['money_add'])) {
    $contract_id       = $_POST["id4"];
    $money_add         = $_POST["money_add"];
    $date_wanted       = $_POST["date_wanted"];
    $comm              = $_POST['comm_add'];
    if(empty($contract_id)||empty($money_add)||empty($comm)){
        $data["msg"] = "<div class='alert alert-danger'>
        <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
        <b>يوجد خطأ رقم العقد أو المبلغ أو الملاحظات في تسجيل البيانات ... راجع  من فضلك</b>
        </div> ";
    }
     
    $comm = htmlspecialchars(strip_tags($comm));
    if(empty($date_wanted)){$date_wanted = date("Y-m-d");}

if(empty($data)){
    $maxsql= $db->prepare("SELECT max(id) as maxd FROM aksat_addition");
        $maxsql->execute();
        if($maxsql->rowCount()>0){$row = $maxsql->fetch(PDO::FETCH_ASSOC);
          $maxD = $row['maxd']+1;} else {$maxD = 1 ; }

   $money_add = round($money_add , 2);
    $sanad = $db->prepare("INSERT INTO aksat_addition(id , contract_id , money_add ,date_wanted ,
                                comm , creator   )
                            VALUES( ? , ? , ? , ? , ? , ? )");
      $sanad->bindParam(1, $maxD);
      $sanad->bindParam(2, $contract_id);
      $sanad->bindParam(3, $money_add);
      $sanad->bindParam(4, $date_wanted);
      $sanad->bindParam(5, $comm);
      $sanad->bindParam(6, $father);
      if ($sanad->execute()) {
        $data["msg"] = "<div class='alert alert-success'>
                                <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                                <b>تم حفظ الإضافي بنجاح...</b>
                                </div>";
      } else {
        $data["msg"] = "<div class='alert alert-danger'>
                                <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
                                <b>يوجد خطأ في تسجيل البيانات ... راجع  من فضلك</b>
                                </div> ";
                            }
    }
    // $data["msg"] = $maxD ;
    echo json_encode($data);
  }
  //
  if (isset($_POST['payMethod'])) {
    $id         = $_POST["id"];
    $payMethod  = $_POST["payMethod"];
    $date_payed = date("Y-m-d");

    $sanad = $db->prepare("UPDATE aksat_addition set payMethod = ?, date_payed = ?, father = ? where id = ?");
      $sanad->bindParam(1, $payMethod);
      $sanad->bindParam(2, $date_payed);
      $sanad->bindParam(3, $father);
      $sanad->bindParam(4, $id);
      if ($sanad->execute()) {
        $data["msg"] = 1;
      } else {
        $data["msg"] = 2;
                            }
     echo json_encode($data);
  }
?>