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

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION["user_id"])) {
    http_response_code(401);
    echo json_encode(array('error' => 'not_authenticated'), JSON_UNESCAPED_UNICODE);
    exit;
}
if (isset($_REQUEST["ct"])) {
    $output = array();
require_once "../../magic/DataBase.php";
 $database = new DataBase();

  $conn = $database->getConnection();

require_once('../../op/wanted.php');
    $contract = $_REQUEST["ct"];
    $carid = 0;
    $cust_id = 0;
    $cust_id2 = 0;
    $father = 0;
    $branch = 0;
    $open_at = 0;
    $closer = 0;
    $cont_status = 0;
    $date_out = null;
    $moneyNew = 0;
   
    $wanted = new  Wanted($conn,$contract) ;
    $pay = $wanted->wanted() ;
    $output["total_in"]     = $pay['total_in'] ;
    $output["total_out"]    = $pay['total_out'] ;
    $output["payed"]        = $pay['payed'];

    $output["days_cost"]    = $pay['days_cost'] ;
    $output["kilos_cost"]   = $pay['kilos_cost'] ;
    $output["hours_cost"]   = $pay['hours_cost'] ;
    $output["kilos_cost"]   = $pay['kilos_cost'] ;
    $output["km_qty"]       = $pay['km_qty'] ;
    $output["used_km"]      = $pay['used_km'] ;
    $output["days_qty"]     = $pay['days_qty'] ;
    $days_qty               = $pay['days_qty'] ;
    $output["hour_qty"]     = $pay['hour_qty'];
    $output["hour_cost"]    = $pay['hour_cost'];
    $output["rent_cost"]    = $pay['rent_cost'] ;
    $output["tot_addtion"]  = $pay['tot_addtion'] ;
    $output["cutt"]         = $pay["cutt"];

    $output["courts_in"]    = $pay['courts_in'] ;
    $output["tot_cut"]      = $pay['tot_cut'] ;
    $output["wesam_ins"]    = $pay['wesam_ins'] ;
    $output["open_kilo"]    = $pay['open_kilo'] ;
    $output["net_cost"]     = $pay['net_cost'] ;
    $output["vat5"]         = $pay['vat5'] ;
    $output["vat15"]        = $pay['vat15'] ;
    $output["vat_req"]      = $pay['vat_req'] ;
    $output["daysCost5"]    = $pay["daysCost5"];
    $output["after_vat"]    = $pay['after_vat'] ;
    $output["wanted"]       = $pay['wanted'] ;

    $netWanted              = $pay['wanted'] ;

    $cont = $conn->prepare("SELECT * FROM contracts where contract_id = ?");
    $cont->bindParam(1, $contract);
    $cont->execute();
if ($cont->rowCount() > 0) { $c_row       = $cont->fetch(PDO::FETCH_ASSOC);
        $carid       = $c_row["carid"];
        $cust_id     = $c_row["cust_id"];
        $cust_id2    = $c_row["cust_id2"];
        $father      = $c_row["father"];
        $branch      = $c_row["branch"];
        $open_at     = $c_row["open_at"];
        $closer      = $c_row["closer"];

        $output["addtion_desc"]     = $c_row["addtion_desc"];
        $output["contract_id"]      = $c_row["contract_id"];
        $output["used_area"]        = $c_row["used_area"];
        $output["rent_days"]        = $c_row["rent_days"];
        $output["carid"]            = $c_row["carid"];
        $output["cust_id"]          = $c_row["cust_id"];
        $output["cust_id2"]         = $c_row["cust_id2"];
        $output["date_out"]         = $c_row["date_out"];
        $date_out                   = $c_row["date_out"];
        $output["date_in"]          = $c_row["date_in"];
        $output["day_cost"]         = $c_row["day_cost"];
        $output["km_out"]           = $c_row["km_out"];
        $output["km_in"]            = $c_row["km_in"];
        $output["time_out"]         = $c_row["time_out"];
        // $output["time_out"]         = date("h:i A", $timeOut);
        $output["time_in"]          = $c_row["time_in"];
        $output["free_kilo"]        = $c_row["free_kilo"];
        $output["kilo_cost"]        = $c_row["kilo_cost"];
        $output["father"]           = $c_row["father"];
        $output["branch"]           = $c_row["branch"];
        $output["free_dd"]          = $c_row["free_dd"];
        $output["tamm"]             = $c_row["tamm"];


        $output["addtion_cost"]     = $c_row["addtion_cost"];
        $output["addtion_desc"]     = $c_row["addtion_desc"];
        $output["violations"]       = $c_row["violations"];
        $output["ins_claim"]        = $c_row["ins_claim"];
        $output["next_cust"]        = $c_row["next_cust"];
        $output["open_kilo_day"]    = $c_row["open_kilo"];
        $output["wesam_ins_day"]    = $c_row["wesam_ins"];
        $output["deduction"]        = $c_row["deduction"];
        
        $output["cont_status"]      = $c_row["cont_status"];
        $cont_status                = $c_row["cont_status"];
        $output["operating_comm"]   = $c_row["operating_comm"];
        $output["dept_comm"]        = $c_row["dept_comm"];
        $output["open_comm"]        = $c_row["open_comm"];
        $output["comm"]             = $c_row["comm"];
    } else {
        http_response_code(404);
        echo json_encode(array('error' => 'contract_not_found'), JSON_UNESCAPED_UNICODE);
        exit;
    }

    // car data 
    $car = $conn->prepare("SELECT cars.brand, cars.kind , cars.model , concat(cars.letters,' ', cars.numbers) as PL,
                cars.color , cars.km3 , cars.minn , cars.freekilo ,
                naql.insurance_no,naql.insurance_kind , naql.insurance_expire ,naql.insurance_money
                FROM cars , naql WHERE cars.carid = naql.carid AND cars.carid = ? LIMIT 1");
    $car->bindParam(1, $carid);
    $car->execute();
    if ($car->rowCount() > 0) {
        $row = $car->fetch(PDO::FETCH_ASSOC);
        $output["brand"]        = $row["brand"];
        $output["kind"]         = $row["kind"];
        $output["model"]        = $row["model"];
        $output["PL"]           = $row["PL"];
        $output["color"]        = $row["color"];

        $output["km3"]          = $row["km3"];
        $output["minn"]         = $row["minn"];
        $output["freekm"]       = $row["freekilo"];

        $output["insurance_no"] = $row["insurance_no"];
        $ins_kind               = $row["insurance_kind"];
        $insurance_money        = $row["insurance_money"];
        $kind = "المسئولية المدنية تجاه الغير";

    switch ( $ins_kind) {
            case '1':      $kind = "المسئولية المدنية تجاه الغير";   break;
            case '2':      $kind = "تغطية ضد الغير - وافي";           break;
            case '3':      $kind = "تأمين شامل";                       break;
        }
       
        $output["insurance_kind"]     = $kind ;
        $output["insurance_expire"]   = $row["insurance_expire"];
        $output["insurance_money"]    = "قبول التغطية التأمينية الإضافية المقدمة من المؤجر-- 
        الوسام المعتمد وسداد قسط تحمل عن كل حادث يشمله التأمين ".$insurance_money." ريال ";
    }
    // custmoer hero data
    $c1 = $conn->prepare("SELECT * FROM customers WHERE cust_id = ? LIMIT 1");
	$c1->bindParam(1,$cust_id);
	$c1->execute();
  if($c1->rowCount() > 0 ){
                $rc = $c1->fetch(PDO::FETCH_ASSOC);
        $output["cust_name"]       = $rc["cust_name"];
        $output["idSA"]            = $rc["idSA"];
        $output["nation"]          = $rc["nation"];
        $output["license"]         = $rc["license"];
        $output["lic_expire"]      = $rc["lic_expire"];
        $output["address"]         = $rc["address"];
        $output["phone"]           = $rc["phone"];
        $output["phone2"]          = $rc["phone2"]??"";

        $output["working_woner"]   = $rc["working_woner"]??"";
        $output["w_phone"]         = $rc["w_phone"]??"";
        $output["w_phone2"]        = $rc["w_phone2"]??"";
        $output["working_address"] = $rc["working_address"]??"";
    }
    // second customer data
    if(!empty($cust_id2)){
        $c2 = $conn->prepare("SELECT * FROM customers WHERE cust_id = ? LIMIT 1");
	    $c2->bindParam(1,$cust_id2);
	    $c2->execute();
    if($c2->rowCount()>0){  $rc2  = $c2->fetch(PDO::FETCH_ASSOC);
        $output["cust_name3"]     = $rc2["cust_name"];
        $output["idSA3"] 		  = $rc2["idSA"];
        $output["nation3"]        = $rc2["nation"];
        $output["license3"]       = $rc2["license"];
        $output["lic_expire3"]    = $rc2["lic_expire"];
        $output["address3"]       = $rc2["address"];
        $output["phone3"]         = $rc2["phone"];
        $output["phone23"]        = $rc2["phone2"]??"";
        
    	$output["working_woner3"] = $rc2["working_woner"]??"";
    	$output["w_phone3"]       = $rc2["w_phone"]??"";
		$output["w_phone23"]      = $rc2["w_phone2"]??"";
		$output["working_address3"] = $rc2["working_address"]??"";
         }
    }else{
        $output["cust_id2"] = 0 ;
    }
    // branch and emp data 
        $emp = $conn->prepare("SELECT branches.b_name , users.realName , branches.address , branches.phone , branches.phone2
                    FROM branches , users WHERE branchID = ? AND user_id = ? LIMIT 1");
        $emp->bindParam(1,$open_at);
        $emp->bindParam(2,$father);
	    $emp->execute();
    if($emp->rowCount()>0){$mass = $emp->fetch(PDO::FETCH_ASSOC);
        $output["realName"]      = $mass["realName"];
        $output["branch"] 	     = $mass["b_name"];
        $output["address4"]      = $mass["address"];
        $output["phone4"] 	     = $mass["phone"];
        $output["phone5"] 	     = $mass["phone2"];
         }
         if(!empty($closer)){
         $emp2 = $conn->prepare("SELECT branches.b_name , users.realName
                    FROM branches , users WHERE branchID = ? AND user_id = ? LIMIT 1");
        $emp2->bindParam(1,$branch);
        $emp2->bindParam(2,$closer);
	    $emp2->execute();
    if($emp2->rowCount()>0){$m2 = $emp2->fetch(PDO::FETCH_ASSOC);
        $output["closer"]      = $m2["realName"];
        $output["branch2"] 	   = $m2["b_name"];
         }}
//autoclose
            if(!empty($output["date_in"])&&($cont_status > 2)){
                $total_in   = $pay['total_in'] ;
                $total_out  = $pay['total_out'] ;
                if($netWanted == 0){
                $close = $conn->prepare("UPDATE contracts SET cont_status = 2 ,total_in = $total_in , wanted = $netWanted , total_out = $total_out 
                where contract_id = $contract LIMIT 1 ");
                $close->execute();
                }
            }
// new contract money
        $tot_in = $conn->prepare("SELECT sum(money_in) as inn from invoice WHERE contract_id = ? AND sanad_date = ?");
        $tot_in->bindParam(1,$contract);
        $tot_in->bindParam(2,$date_out);
        $tot_in->execute();
    if ($tot_in->rowCount() > 0) {
        $toty_in        = $tot_in->fetch(PDO::FETCH_ASSOC);
        $moneyNew       = $toty_in["inn"];
    }
    if(empty($moneyNew)) $moneyNew = 0;
        $output["newMoney"] = $moneyNew ;

         echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
        // echo $output;
        //  echo '<pre>'; print_r($output) ; echo '</pre>';
}
