<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kapus{

   public function calc($date,$userID = 3)
   {
      $CI =& get_instance();
      $this->db = $CI->load->database("onedev",true);
      //cek if current date is posted 
      $this->db->trans_start();
      $sql = "select * from sys_f_kapus_sum where sysFKapusSumDate = ? 
         and sysFKapusIsActive = 'Y' ";
      $qry = $this->db->query($sql , array($date));
      $sysFKapusSumID = 0;
      if ($qry ) {
         $rows = $qry->result_array();
         if ( count($rows) > 0 )  {
            $sysFKapusSumID = $rows[0]["sysFKapusSumID"];
            if ($rows[0]["sysFKapusSumIsPosted"] == "Y" ) {
               return array("status" => "ERR" , "message" => "Kapus at $date already posted");
            }
         } 
         
      }



      $sql = "select * from sys_kapus limit 0,1";
      $qry = $this->db->query($sql);
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Invalid Kapus Setting" . print_r($this->db->error(),true));
      }
      $rows = $qry->result_array();
      if (count($rows) == 0 ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Invalid Kapus Setting");
      }
      $companyID = $rows[0]["sysKaPusM_CompanyID"] . "," . $rows[0]["sysKaPusM_CompanyID2"];
      $paymentTypeID = $rows[0]["sysKaPusM_PaymentTypeID"];
      $targetPct = $rows[0]["sysKaPusPct"];
      // get kapus
      $sql = "select sum(F_PaymentDetailAmount) TotalAmount,
         sum(F_PaymentDetailAmount - F_PaymentDetailAmount mod 500 ) TotalAmountAfterRounding
         from t_orderheader 
         join f_payment on T_OrderHeaderID = F_PaymentT_OrderHeaderID 
         and F_PaymentIsActive = 'Y' and T_OrderHeaderIsActive = 'Y' 
         and date(T_OrderHeaderDate) = date(?)
         and F_PaymentDate = date(?)
         join f_paymentdetail on F_PaymentID = F_PaymentDetailF_PaymentID 
         and F_PaymentDetailM_PaymentTypeID = ?
         and F_PaymentDetailIsActive = 'Y' ";
      $qry = $this->db->query($sql, array($date,$date, $paymentTypeID));
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Error get total payment " . print_r($this->db->error(),true));
      }
      $rows = $qry->result_array();
      if (count($rows) == 0 ) {
         $this->db->trans_rollback();
         return array("status" => "OK" , "message" => "No Payment Type , $paymentTypeID , $date ");
      }
      // seluruh kas 
      $totalAmount = $rows[0]["TotalAmount"];
      $totalAmountAfterRounding = $rows[0]["TotalAmountAfterRounding"];
      if ($totalAmount == 0 ) {
         $this->db->trans_rollback();
         return array("status" => "OK" , "message" => "Total Amount Zero ");
      }

      $sql = "drop table if exists xtmp_kapus";
      $qry = $this->db->query($sql);
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Drop Tmp table " . print_r($this->db->error(),true));
      }
      $sql = "
        create temporary table xtmp_kapus
        select F_PaymentT_OrderHeaderID, 
        cast(sum(F_PaymentDetailAmount) as decimal(15,0)) Total 
        from f_payment 
        join t_orderheader on F_PaymentT_OrderHeaderID = T_OrderHeaderID and T_OrderHeaderM_CompanyID in ($companyID)
        join f_paymentdetail on F_PaymentDetailF_PaymentID = F_PaymentID  and F_PaymentDetailIsActive = 'Y'
            and F_PaymentIsActive = 'Y'
        where F_PaymentDate = ? and F_PaymentDetailM_PaymentTypeID = ?
         group by F_PaymentT_OrderHeaderID";
      $qry = $this->db->query($sql, array($date,$paymentTypeID));
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Create Tmp table " . print_r($this->db->error(),true));
      }

      $sql = "
        select T_OrderHeaderID, 
        cast(T_OrderHeaderTotal as decimal(15,0) ) as T_OrderHeaderTotal ,
        cast(T_OrderHeaderTotal - T_OrderHeaderTotal mod 500 as decimal(15,0) ) as T_OrderHeaderTotalAfterRounding 
        from t_orderheader
        join xtmp_kapus on T_OrderHeaderID = F_PaymentT_OrderHeaderID 
            and Total = T_OrderHeaderTotal
            and date(T_OrderHeaderDate) = ?
        order by T_OrderHeaderID";
      $qry = $this->db->query($sql, array($date));
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Error get detail payment " . print_r($this->db->error(),true));
      }
      $rows = $qry->result_array();

      if ($sysFKapusSumID == 0) {
         $sql = "insert into sys_f_kapus_sum(sysFKapusSumDate, sysFKapusSumUserID,sysFKapusSumTargetPct,
            sysFKapusSumTotal, sysFKapusSumTotalAfterRounding) values(?,?,?,?,?)";
         $qry = $this->db->query($sql,array($date, $userID, $targetPct, $totalAmount, $totalAmountAfterRounding));
         if (! $qry ) {
            $this->db->trans_rollback();
            return array("status" => "ERR" , "message" => "Error create sysFKapusSum " . print_r($this->db->error(),true));
         }
         $sysFKapusSumID = $this->db->insert_id();
      }	
      $qry = $this->db->query("update sys_f_kapus set sysFKapusIsActive='N' where sysFKapusSysFKapusSumID=?", array($sysFKapusSumID));
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Error reset sysFKapus " . print_r($this->db->error(),true));
      }

      $sql_i = "insert into sys_f_kapus( sysFKapusT_OrderHeaderID, sysFKapusAmount, sysFKapusRunAmount, 
         sysFKapusAmountAfterRounding,
         sysFKapusM_UserID, sysFKapusDate, sysFKapusPct, sysFKapusSysFKapusSumID )
         values(?,?,?, ?, ?,?,?,?)";
      $curPct = 0;
      $sum_total = 0;
      $sum_total_after_rounding = 0;
      foreach($rows as $r) {
         $x_id = $r["T_OrderHeaderID"];
         $x_total = $r["T_OrderHeaderTotal"];
         $x_total_after_rounding = $r["T_OrderHeaderTotalAfterRounding"];
         $sum_total += $x_total;
         $sum_total_after_rounding += $x_total_after_rounding;
         $curPct = $sum_total / $totalAmount * 100 ;
         $qry = $this->db->query($sql_i, array($x_id, $x_total, $sum_total,
            $x_total_after_rounding,
            $userID,$date, $curPct,$sysFKapusSumID ) );
         if (! $qry ) {
            $this->db->trans_rollback();
            return array("status" => "ERR" , "message" => "Error insert sys_f_kapus " . print_r($this->db->error(),true));
         }
         if ($curPct >= $targetPct ) {
            break;
         } 
      }
      $sql = "update sys_f_kapus_sum set sysFKapusSumAmount = ? , sysFKapusSumActualPct = ? ,
         sysFKapusSumTargetPct = ?, sysFKapusSumAmountAfterRounding = ?
         where sysFKapusSumID = ?";
      $qry = $this->db->query($sql, array($sum_total, $curPct, $targetPct, $sum_total_after_rounding, $sysFKapusSumID));
      if (! $qry ) {
         $this->db->trans_rollback();
         return array("status" => "ERR" , "message" => "Error update sysFKapusSum " . print_r($this->db->error(),true));
      }
      $this->db->trans_commit();
      return array("status" => "OK" , "message" => "");
   }

}
