<?php

class Usergroup extends MY_Controller
{
   var $db_onedev;
   public function index()
   {
      echo "USER GROUP REPORT API";
   }
   public function __construct()
   {
      parent::__construct();
      $this->db_onedev = $this->load->database("onedev", true);
   }
	
    function lookupuserbyname(){
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
    
            $prm = $this->sys_input;
            $groupname = $prm['groupname'];
            $filter = '';
            if(isset($sexid)){
                $filter .= "AND ($sexid = 0 or ($sexid > 0 and Nat_SexID = $sexid)) ";
            }
            if(isset($flagid)){
                $filter .= "AND ($flagid = 0 or ($flagid > 0 and Nat_FlagID = $flagid))";
            }
            $limit = '';
            if($all == 'N'){
                $limit = ' LIMIT 10';
            }
            $number_limit = 10;
            $number_offset = ($prm['current_page'] - 1) * $number_limit ;
            $sql = "select COUNT(*) as total
			FROM(SELECT *
                    from m_usergroup 
                    WHERE
                     M_UserGroupIsActive = 'Y' AND
                     M_UserGroupName like '%{$groupname}%' 
                     $filter GROUP BY M_UserGroupID) a";
          //  $total = $this->db_onedev->query($sql,$sql_param)->row()->total;
          $query = $this->db_onedev->query($sql);
          //echo $this->db_onedev->last_query();
          $tot_count = 0;
          $tot_page = 0;
          if ($query) {
             $tot_count = $query->result_array()[0]["total"];
             $tot_page = ceil($tot_count/$number_limit);
          } else {
             $this->sys_error_db("m_usergroup count", $this->db_onedev);
             exit;
          }
            
            $sql = "SELECT m_usergroup.*,
            M_UserGroupID as id,
            M_UserGroupID,
            M_UserGroupName
FROM m_usergroup
WHERE
M_UserGroupIsActive = 'Y' AND
M_UserGroupName like '%{$groupname}%' 
$filter
                        GROUP BY M_UserGroupID
                        ORDER BY M_UserGroupName ASC
                        limit $number_limit offset $number_offset";
            $sql_param = array($search);
            $query = $this->db_onedev->query($sql);
           // echo $this->db_onedev->last_query();
            if ($query) {
                $rows = $query->result_array();
                
                
            } else {
              $this->sys_error_db("m_usergroup select");
              exit;
            }
    
            $result = array ("total" => $tot_page, "total_filter"=>count($rows),"records" => $rows);
            $this->sys_ok($result);
    
        } catch(Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    function lookupreportbyid(){
        try {
            //# cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
    
            $prm = $this->sys_input;
            $id = $prm['id'];
            $reportgroup = $prm['reportgroup'];
            $reportcode = $prm['reportcode'];
            $reportname = $prm['reportname'];
            $status = $prm['status'];
            $all = $prm['all'];
            $filter = '';
            if($status != 'A'){
                $filter .= "AND status = '{$status}' ";
            }else{
                $filter .= "";
            }
            $limit = '';
            if($all == 'N'){
                $limit = ' LIMIT 10';
            }
            $number_limit = 10;
            $number_offset = ($prm['current_page'] - 1) * $number_limit ;
            $sql = "select COUNT(*) as total
			FROM(SELECT *, IF(IFNULL(UserGroupReportID,0) > 0 , 'Y', 'N') as status
                    from r_report
                    LEFT JOIN usergroup_report ON R_ReportID = UserGroupReportR_ReportID AND UserGroupReportM_UserGroupID = $id AND UserGroupReportIsActive = 'Y'
                    LEFT JOIN m_usergroup ON UserGroupReportM_UserGroupID = M_UserGroupID AND M_UserGroupIsActive = 'Y'
                    LEFT JOIN r_reportgroup ON R_ReportR_ReportGroupID = R_ReportGroupID
                    WHERE
                    R_ReportIsActive = 'Y') a
                    WHERE
                    R_ReportGroupName like '%{$reportgroup}%' AND
                    R_ReportCode like '%{$reportcode}%' AND
                    R_ReportName like '%{$reportname}%' $filter";
          //  $total = $this->db_onedev->query($sql,$sql_param)->row()->total;
          $query = $this->db_onedev->query($sql);
          //echo $this->db_onedev->last_query();
          $tot_count = 0;
          $tot_page = 0;
          if ($query) {
             $tot_count = $query->result_array()[0]["total"];
             $tot_page = ceil($tot_count/$number_limit);
          } else {
             $this->sys_error_db("r_report count", $this->db_onedev);
             exit;
          }
            
            $sql = "SELECT * FROM(select R_ReportID as id,
            R_ReportID,
            R_ReportCode,
            R_ReportName,
            R_ReportGroupName,
            UserGroupReportID,
            UserGroupReportM_UserGroupID,
            UserGroupReportR_ReportID,
            IF(IFNULL(UserGroupReportID,0) > 0 , 'Y', 'N') as status
                from r_report
                LEFT JOIN usergroup_report ON R_ReportID = UserGroupReportR_ReportID AND UserGroupReportM_UserGroupID = $id AND UserGroupReportIsActive = 'Y'
                LEFT JOIN m_usergroup ON UserGroupReportM_UserGroupID = M_UserGroupID AND M_UserGroupIsActive = 'Y'
                LEFT JOIN r_reportgroup ON R_ReportR_ReportGroupID = R_ReportGroupID
                WHERE       
                R_ReportIsActive = 'Y') a
                WHERE      
                R_ReportGroupName like '%{$reportgroup}%' AND 
                R_ReportCode like '%{$reportcode}%' AND
                R_ReportName like '%{$reportname}%' $filter
                GROUP BY R_ReportID
                ORDER BY R_ReportGroupName ASC, R_ReportName ASC
                    limit $number_limit offset $number_offset";
            $sql_param = array($search);
            $query = $this->db_onedev->query($sql);
            //echo $this->db_onedev->last_query();
            if ($query) {
                $rows = $query->result_array();
                
                
            } else {
              $this->sys_error_db("r_report select");
              exit;
            }
    
            $result = array ("total" => $tot_page, "total_filter"=>count($rows),"records" => $rows);
            $this->sys_ok($result);
    
        } catch(Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
    function getsexreg(){
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $rows = [];
    $query ="	
    SELECT 'A' as M_StatusID, 'Semua' as M_StatusName
    UNION
    SELECT 'Y' as M_StatusID, 'Terpilih' as M_StatusName
    UNION
    SELECT 'N' as M_StatusID, 'Belum Terpilih' as M_StatusName   
    ";
    //echo $query;
    $rows['f_statuss'] = $this->db_onedev->query($query)->result_array();
        
        $result = array(
            "total" => count($rows) , 
            "records" => $rows, 
    	); 
        $this->sys_ok($result);
        exit;
    }
    function getstatus(){
        if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
        }
        $rows = [];

    $query ="	
    SELECT 'A' as M_StatusID, 'Semua' as M_StatusName
    UNION
    SELECT 'Y' as M_StatusID, 'Terpilih' as M_StatusName
    UNION
    SELECT 'N' as M_StatusID, 'Belum Terpilih' as M_StatusName   
    ";
    //echo $query;
    $rows['f_statuss'] = $this->db_onedev->query($query)->result_array();
        
        $result = array(
            "total" => count($rows) , 
            "records" => $rows, 
    	); 
        $this->sys_ok($result);
        exit;
    }
   public function addnewreport()
   {
      try {
         //# cek token valid
         if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
         }

         //# ambil parameter input
         $prm = $this->sys_input;
         $userid = $prm['userid'];
         $reportcode = $prm['reportcode'];
         $reportname = $prm['reportname'];
         $userid = $this->sys_user["M_UserID"]; 
         
         $sql = "insert into r_report(	
            R_ReportCode,
            R_ReportName,
            R_ReportUserID,
            R_ReportCreated,
            R_ReportLastUpdated
            )
                 values(?,?,?,now(),now())";
    $query = $this->db_onedev->query($sql,
    array(
        $reportcode,
        $reportname,
        $userid
    )
    );
    if (!$query) {
    $this->sys_error_db("m_usergroup insert",$this->db_onedev);
    exit;
    }
        $last_id = $this->db_onedev->insert_id();
        $result = array ("total" => 1, "records" => array("xid" => 0));
        $this->sys_ok($result);
         
         

      } catch(Exception $exc) {
         $message = $exc->getMessage();
         $this->sys_error($message);
      }
   }
   public function saveaddeditreport()
   {
      try {
         //# cek token valid
         if (! $this->isLogin) {
            $this->sys_error("Invalid Token");
            exit;
         }

         //# ambil parameter input
         $prm = $this->sys_input;
         $usergroupid = $prm['userid'];
         $reportid = $prm['R_ReportID'];
         $reportuserid = $prm['UserGroupReportID'];
         $status = $prm['status'];
         $userid = $this->sys_user["M_UserID"]; 
         if($status == 'Y'){
            $sql = "insert into usergroup_report(	
                UserGroupReportM_UserGroupID,
                UserGroupReportR_ReportID,
                UserGroupUserID,
                UserGroupReportCreated,
                UserGroupReportLastUpdated
                )
                     values(?,?,?,now(),now())";
        $query = $this->db_onedev->query($sql,
        array(
            $usergroupid,
            $reportid,
            $userid
        )
        );
        if (!$query) {
        $this->sys_error_db("usergroup_report insert",$this->db_onedev);
        exit;
        }
            $last_id = $this->db_onedev->insert_id();
            $result = array ("total" => 1, "records" => array("xid" => 0));
            $this->sys_ok($result);
             
         }else{
            $sql = "UPDATE usergroup_report SET	
                UserGroupReportIsActive = 'N',
                UserGroupUserID = ?,
                UserGroupReportCreated = now(),
                UserGroupReportLastUpdated = now()
                WHERE UserGroupReportID = ?";
        $query = $this->db_onedev->query($sql,
        array(
            $userid,
            $reportuserid
        )
        );
        if (!$query) {
        $this->sys_error_db("usergroup_report insert",$this->db_onedev);
        exit;
        }
            $last_id = $this->db_onedev->insert_id();
            $result = array ("total" => 1, "records" => array("xid" => 0));
            $this->sys_ok($result);
         }
         
         

      } catch(Exception $exc) {
         $message = $exc->getMessage();
         $this->sys_error($message);
      }
   }
   function saveallreport(){
    if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
    }
    $prm = $this->sys_input;
    $details = $prm['details'];
    $userid = $this->sys_user["M_UserID"];
    foreach($details as $k => $v){
        $query = "UPDATE usergroup_report SET 
            UserGroupReportM_UserGroupID = '{$v['UserGroupReportM_UserGroupID']}',	
            UserGroupReportAdviceIna = '{$v['UserGroupReportAdviceIna']}',	
            UserGroupReportAdviceEng = '{$v['UserGroupReportAdviceEng']}',
            UserGroupReportUserID = {$userid},
            UserGroupReportCreated = now(),	
            UserGroupReportLastUpdated = now()
            WHERE UserGroupReportID = {$v['UserGroupReportID']}";
        
    //echo $query;
    $action = $this->db_onedev->query($query);
    }
    
    
    if($action){
        $result = array(
            "total" => 1 , 
            "records" => array(), 
        ); 
        $this->sys_ok($result);
        exit;
    }
    else{
        $this->sys_error_db($this->db_onedev->last_query(), $this->db_onedev);
        exit;
    }
    
}
   public function deleteuser()
   {
    try {
        //# cek token valid
        if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
        }

        //# ambil parameter input
        $prm = $this->sys_input;
        $userid = $this->sys_user["M_UserID"];
        $sql = "update nat_methode SET 
        Nat_MethodeIsActive = 'N'
				WHERE
				Nat_MethodeID = ?
            
				";

            $query = $this->db_onedev->query($sql,
                array(
                    $prm['id']
                )
            );
           // echo $query;
            if (!$query) {
                $this->sys_error_db("nat_methode delete");
                exit;
            } 
            $sql = "update m_usergroup SET 
            M_UserGroupIsActive = 'N'
                    WHERE
                    M_UserGroupNat_MethodeID = ?
                
                    ";
    
                $query = $this->db_onedev->query($sql,
                    array(
                        $prm['id']
                    )
                );
               // echo $query;
                if (!$query) {
                    $this->sys_error_db("m_usergroup delete");
                    exit;
                } 
                
                    
        $result = array ("total" => 1, "records" => array("xid" => 0));
        $this->sys_ok($result);

    } catch(Exception $exc) {
        $message = $exc->getMessage();
        $this->sys_error($message);
    }
   }
   public function deletereport()
   {
    try {
        //# cek token valid
        if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
        }

        //# ambil parameter input
        $prm = $this->sys_input;
        $userid = $this->sys_user["M_UserID"];
            $sql = "update m_usergroup SET 
            M_UserGroupIsActive = 'N'
                    WHERE
                    M_UserGroupID = ?
                
                    ";
    
                $query = $this->db_onedev->query($sql,
                    array(
                        $prm['id']
                    )
                );
               // echo $query;
                if (!$query) {
                    $this->sys_error_db("m_usergroup delete");
                    exit;
                } 

               
        $result = array ("total" => 1, "records" => array("xid" => 0));
        $this->sys_ok($result);

    } catch(Exception $exc) {
        $message = $exc->getMessage();
        $this->sys_error($message);
    }
   }
  
    function searchuser(){
        if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
        }
        $prm = $this->sys_input;
    
        $max_rst = 12;
        $tot_count =0;
    
        $q = [
            'search'     => '%'
        ];
    
        if ($prm['search'] != '')
        {
            $q['search'] = "%{$prm['search']}%";  
        }
    
          // QUERY TOTAL
        $sql = "SELECT count(*) as total
                FROM nat_methode
                WHERE 
                Nat_MethodeName like ?
                AND Nat_MethodeIsActive = 'Y'";
        $query = $this->db_onedev->query($sql,$q['search']);
        //echo $query;
        if ($query) { 
            $tot_count = $query->result_array()[0]["total"]; 
        } 
        else {
            $this->sys_error_db("nat_methode count",$this->db_onedev);
            exit;
        }
    
        $sql = "
        SELECT Nat_MethodeID, Nat_MethodeName
        FROM nat_methode
            WHERE 
            Nat_MethodeName like ?
            AND Nat_MethodeIsActive = 'Y'
            ORDER BY Nat_MethodeName ASC
          ";
          $query = $this->db_onedev->query($sql, array($q['search']));
            
          if ($query) { 
             $rows = $query->result_array();
             //echo $this->db_onedev->last_query();
             $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows));
             $this->sys_ok($result);
          } 
          else {
             $this->sys_error_db("nat_methode rows",$this->db_onedev);
             exit;
          }
    }
    function searchuserbyname(){
        if (! $this->isLogin) {
        $this->sys_error("Invalid Token");
        exit;
        }
        $prm = $this->sys_input;
    
        $max_rst = 12;
        $tot_count =0;
    
        $q = [
            'search'     => '%'
        ];
    
        if ($prm['search'] != '')
        {
            $q['search'] = "%{$prm['search']}%";  
        }
    
          // QUERY TOTAL
        $sql = "SELECT count(*) as total
                FROM nat_methode
                WHERE 
                Nat_MethodeName like ?
                AND Nat_MethodeIsActive = 'Y'";
        $query = $this->db_onedev->query($sql,$q['search']);
        //echo $query;
        if ($query) { 
            $tot_count = $query->result_array()[0]["total"]; 
        } 
        else {
            $this->sys_error_db("nat_methode count",$this->db_onedev);
            exit;
        }
    
        $sql = "
        SELECT Nat_MethodeID, Nat_MethodeName
        FROM nat_methode
            WHERE 
            Nat_MethodeName like ?
            AND Nat_MethodeIsActive = 'Y'
            ORDER BY Nat_MethodeName ASC
          ";
          $query = $this->db_onedev->query($sql, array($q['search']));
            
          if ($query) { 
             $rows = $query->result_array();
             //echo $this->db_onedev->last_query();
             $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows));
             $this->sys_ok($result);
          } 
          else {
             $this->sys_error_db("nat_methode rows",$this->db_onedev);
             exit;
          }
    }
    
    
function searchtest(){
    if (! $this->isLogin) {
    $this->sys_error("Invalid Token");
    exit;
    }
    $prm = $this->sys_input;

    $max_rst = 12;
    $tot_count =0;

    $q = [
        'search'     => '%'
    ];

    if ($prm['search'] != '')
    {
        $q['search'] = "%{$prm['search']}%";  
    }

      // QUERY TOTAL
    $sql = "SELECT count(*) as total
            FROM t_test
            WHERE 
            T_TestName like ?
            AND T_TestIsActive = 'Y' AND T_TestIsResult = 'Y'";
    $query = $this->db_onedev->query($sql,$q['search']);
    //echo $query;
    if ($query) { 
        $tot_count = $query->result_array()[0]["total"]; 
    } 
    else {
        $this->sys_error_db("t_test count",$this->db_onedev);
        exit;
    }

    $sql = "
        SELECT *
        FROM t_test
        WHERE 
        T_TestName like ?
        AND T_TestIsActive = 'Y' AND T_TestIsResult = 'Y'
        ORDER BY T_TestName ASC
      ";
      $query = $this->db_onedev->query($sql, array($q['search']));
        
      if ($query) { 
         $rows = $query->result_array();
         //echo $this->db_onedev->last_query();
         $result = array("total" => $tot_count, "records" => $rows, "total_display" => sizeof($rows));
         $this->sys_ok($result);
      } 
      else {
         $this->sys_error_db("t_test rows",$this->db_onedev);
         exit;
      }
}
}