<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Reports extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->is_logged_in();
        $this->load->library('form_validation');
        ($this->verify_min_level(1)) ? '' : redirect('login');
    }
    public function index()
    {
        if(isset($_POST['submit']))
        {
           
             $from_date = $this->input->post('from_date');
            $to_date = $this->input->post('to_date');
           
            $view_data['from_date'] = $from_date;
            $view_data['to_date'] = $to_date;
            $view_data['records'] = $this->datatable($from_date,$to_date); 
             // print_r($view_data['records'] );exit();
            $data = array(
                'title' => 'Reports',
                'page' => 'Reports',
                'content' => $this->load->view('reports/report', $view_data, true),
            );
    
            $this->load->view('base/main_template', $data);
       
        }else  if(isset($_POST['today_submit'])) {
            

            $view_data['records'] = $this->datatable2(); 
           
            $data = array(
                'title' => 'Reports',
                'page' => 'Reports',
                'content' => $this->load->view('reports/report', $view_data, true),
            );
    
            $this->load->view('base/main_template', $data);

           
            
        }else{

            $view_data['records'] = $this->datatable1();
            $data = array(
                'title' => 'Reports',
                'page' => 'Reports',
                'content' => $this->load->view('reports/report', $view_data, true),
            );
    
            $this->load->view('base/main_template', $data);

        }
        
        
    }

    public function datatable2($from_date='',$to_date='')
    {
        $this->db->select('*,ds.id as ds_id,cu.customer as customer,des.description as description,v.mode_of_vehicle as mode_of_vehicle,d.place_of_delivery as place_of_delivery,cu.id as customer_id');
        $this->db->from('daily_status as ds');
        $this->db->join('agent as a', 'a.id = ds.agent','left');
        $this->db->join('mode_of_vehicle as v', 'v.id = ds.vehicle_mode','left');
        $this->db->join('remarks as r', 'r.id = ds.remark','left');
        $this->db->join('supplier as s', 's.id = ds.supplier','left');
        $this->db->join('customer as cu', 'cu.id = ds.customer','left');
        $this->db->join('description as des', 'des.id = ds.description','left');
        $this->db->join('place_of_delivery as d', 'd.id = ds.place_of_delivery','left');
        $this->db->where('ds.remark_status',1);
        $this->db->where('ds.date_of_clearance >=', date('Y-m-d'));

        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }


    public function datatable1($from_date='',$to_date='')
    {
        $this->db->select('*,ds.id as ds_id,cu.customer as customer,des.description as description,v.mode_of_vehicle as mode_of_vehicle,d.place_of_delivery as place_of_delivery,cu.id as customer_id');
        $this->db->from('daily_status as ds');
        $this->db->join('agent as a', 'a.id = ds.agent','left');
        $this->db->join('mode_of_vehicle as v', 'v.id = ds.vehicle_mode','left');
        $this->db->join('remarks as r', 'r.id = ds.remark','left');
        $this->db->join('supplier as s', 's.id = ds.supplier','left');
        $this->db->join('customer as cu', 'cu.id = ds.customer','left');
        $this->db->join('description as des', 'des.id = ds.description','left');
        $this->db->join('place_of_delivery as d', 'd.id = ds.place_of_delivery','left');
        $this->db->where('ds.remark_status',1);
        // $this->db->where('ds.date_of_clearance >=', date('Y-m-d'));

        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }

        

    // public function today_clearance()
    // {
     
    //         $view_data['records'] = $this->mcommom->records_all('daily_status',array('date_of_clearanace>='=>date('Y-m-d')));
    //          // print_r($view_data['records'] );exit();
    //         $data = array(
    //             'title' => 'Reports',
    //             'page' => 'Reports',
    //             'content' => $this->load->view('reports/report', $view_data, true),
    //         );
    
    //         $this->load->view('base/main_template', $data);
       
        
        
    // }
     public function delete($id){    
        
        $delete=$this->mcommon->common_delete('daily_status',array('id'=>$id));
        if($delete){
            $this->session->set_flashdata('alert_danger','Report Deleted successfully !!!');
        }else{
            $this->session->set_flashdata('alert_warning','Error in Deleting Report');
        }
        redirect('Reports');
    }
    
    public function datatable($from_date='',$to_date='')
    {
        $this->db->select('*,ds.id as ds_id,cu.customer as customer,des.description as description,v.mode_of_vehicle as mode_of_vehicle,d.place_of_delivery as place_of_delivery,cu.id as customer_id');
        $this->db->from('daily_status as ds');
        $this->db->join('agent as a', 'a.id = ds.agent','left');
        $this->db->join('mode_of_vehicle as v', 'v.id = ds.vehicle_mode','left');
        $this->db->join('remarks as r', 'r.id = ds.remark','left');
        $this->db->join('supplier as s', 's.id = ds.supplier','left');
        $this->db->join('customer as cu', 'cu.id = ds.customer','left');
        $this->db->join('description as des', 'des.id = ds.description','left');
        $this->db->join('place_of_delivery as d', 'd.id = ds.place_of_delivery','left');
        $this->db->where('ds.remark_status',1);
       
       
        $from_date = date('Y-m-d', strtotime($from_date));

        $to_date = date('Y-m-d', strtotime($to_date));
      
       

         if (!empty($from_date) && !empty($to_date)) {

          
                $this->db->where('ds.date_of_clearance >=', $from_date);
                $this->db->where('ds.date_of_clearance <=', $to_date);
                  $this->db->order_by('ds.date_of_clearance', 'asc');

            
           
        }
        // $query = $this->db->get();
        // $result = $query->result();
        // // return $result;
        // echo "<pre>";
        // print_r($result);
        // echo "</pre>";
        // die();
      
        $query = $this->db->get();
        $result = $query->result();
        return $result;
    }


 


    public function send_mail(){

        $count = $this->mcommon->record_counts('daily_status');
        $customer_id = $this->input->post('customer_id');
        $mail_send = $this->input->post('mail_send');
        if($mail_send==1){
    
        $this->db->distinct();
        $this->db->select('customer');
        $this->db->from('daily_status');
        $this->db->where('customer',$customer_id);
        
        $query = $this->db->get();
        $customers = $query->result_array();
        // print_r($customers);exit();
    
        $records = []; 
        for ($i = 0; $i < $count; $i++) {
            $email_check[] = $this->input->post('emailcheck'.$i) == 1 ? $this->input->post('emailcheck' . $i) : 0;
            $id[] = $this->input->post('id' . $i);
            if ($email_check[$i] == 1) {
                $this->db->select('*,ds.id as ds_id');
                $this->db->from('daily_status as ds');
                $this->db->join('agent as a', 'a.id = ds.agent','left');
                $this->db->join('mode_of_vehicle as v', 'v.id = ds.vehicle_mode','left');
                $this->db->join('remarks as r', 'r.id = ds.remark','left');
                $this->db->join('supplier as s', 's.id = ds.supplier','left');              
                $this->db->join('description as des', 'des.id = ds.description','left');
                $this->db->join('place_of_delivery as d', 'd.id = ds.place_of_delivery','left');
                $this->db->where('ds.id', $id[$i]);
                $query = $this->db->get();
                $records[] = $query->result();
            }
        }
        $result = [];
        foreach($customers as $customer){
            $customer_id = $customer['customer'];
            for ($i=0;$i<count($records); $i++) {
                if (!isset($result)) {
                    $result = [];
                }
                if($records[$i][0]->customer==$customer_id){
                $result[$i] = $records[$i][0];
                }
            }
            $view_data['records']=$result;
            $view_data['customer']=$this->mcommon->specific_row_value('customer',array('id'=>$customer_id),'customer');
            $from_mail=$this->mcommon->specific_row_value('em_companies',"",'company_email');
            $cc_email=$this->mcommon->specific_row_value('em_companies',"",'email_cc');
            $email=$this->mcommon->records_all('customer_email',array('customer_id'=>$customer_id));
            // $to_email=$email[0]->email?$email[0]->email:0;
            // for($i=0;$i<count($email);$i++){
            //     $to_email=$email[$i]->email;

                $mailtemplate = $this->load->view('daily_status/is_confirmed_email', $view_data, true);
                $apiUrl = 'https://api.brevo.com/v3/smtp/email';
                $apiKey = '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';
                
                $name='Arrowshipping';
               
                   $subject="Arrowshipping - Clearance Status";
                           
                
                $data = [
                    'sender' => [
                        'name' => $name,
                        'email' => $from_mail
                    ],
                    'to' => [],

                    'cc' => [
                        
                        [
                            'email' => $cc_email,
                            
                        ],
                    ],
                    'htmlContent' => $mailtemplate,
                    'textContent' => 'Enquiry Form',
                    'subject' => $subject
                ];
                
                for ($i = 0; $i < count($email); $i++) {
                    $to_email = $email[$i]->email;
                    $data['to'][] = [
                        'email' => $to_email,
                        // 'name' => $customer_name
                    ];
                }
            
            
                $jsonData = json_encode($data);
                $ch = curl_init($apiUrl);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'accept: application/json',
                    'api-key: ' . $apiKey,
                    'content-type: application/json'
                ]);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $response = curl_exec($ch);
                // Check for errors
                if (curl_errno($ch)) {
                    echo 'cURL error: ' . curl_error($ch);
                } else {
                    // Process the response
                header("Location:index.php");
                }
                
                // Close cURL session
                curl_close($ch);
                
                $mail_status = 1;
                // print_r($mail_status);exit();
               
                unset($result,$mailtemplate);


            // }
        }
           
        } 
    
        // echo $mail_status;exit;
        if($mail_status >= 1){       
        $this->session->set_flashdata('alert_success', 'Mail sent to the customers successfully !!!'); 
        redirect('Reports');
        }
        else{
            $this->session->set_flashdata('alert_danger', 'Mail not sent'); 
        redirect('Reports');
        }
        
         
    }  
}
