<?php
require "vendor/autoload.php";
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
use Dompdf\Dompdf;

class Donation extends MY_Controller {

    public function __construct() {
        parent::__construct();
        error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
        $this->load->model('model_customer');
    }


    //show admin list
    public function index() {
        $admin_id = $this->session->userdata("ADMIN_ID");
        $data['title'] = dt_translate('manage') . " " . dt_translate('donation');
        $order = "app_donation.created_on DESC";

        $dep_join = array(
            array(
                'table' => 'app_donation_category',
                'condition' => 'app_donation_category.id=app_donation.category_id',
                'jointype' => 'inner'
            )
        );
        $condition="";
        if($this->session->userdata("TYPE")=="A"){
            $condition.=" payment_status='success' AND donation_type='donation' ";
        }else{
            $condition.=" payment_status='success' AND donation_type='donation' AND created_by=".$admin_id;
        }

        $admin = $this->model_customer->getData("app_donation", "app_donation.*,app_donation_category.title", $condition, $dep_join, $order);
        $orders = "title  ASC";
        $data['app_donation_category'] = $this->model_customer->getData("app_donation_category", "*", "status='A'", "", $orders);
        $data['donation_data'] = $admin;
        $this->load->view('admin/donation/index', $data);
    }

    //show add admin form
    public function add_donation() {

        $data['title'] = dt_translate('add') . " " . dt_translate('donation');
        $order = "title  ASC";
        $data['app_donation_category'] = $this->model_customer->getData("app_donation_category", "*", "status='A'", "", $order);
        $this->load->view('admin/donation/add_update', $data);
    }

    //show edit admin form
    public function update_donation($id) {
        $id = (int) $id;
        $admin = $this->model_customer->getData("app_donation", "*", "id='$id'");
        if (empty($admin)) {
            $this->session->set_flashdata('msg', dt_translate('invalid_request'));
            $this->session->set_flashdata('msg_class', 'failure');
            redirect('donation');
        }

        if (isset($admin[0]) && !empty($admin[0])) {

            $order = "title  ASC";
            $data['app_donation_category'] = $this->model_customer->getData("app_donation_category", "*", "status='A'", "", $order);

            $data['donation_data'] = $admin[0];
            $data['title'] = dt_translate('update') . " " . dt_translate('donation');
            $this->load->view('admin/donation/add_update', $data);
        } else {
            redirect('admin/donation');
        }
    }

    //add/edit an admin
    public function save_donation() {
        $admin_id = $this->session->userdata("ADMIN_ID");

        $id = (int) $this->input->post('id', true);
        $this->form_validation->set_rules('first_name', dt_translate('first_name'), 'trim|required');
        $this->form_validation->set_rules('last_name', dt_translate('last_name'), 'trim|required');
        $this->form_validation->set_rules('city', dt_translate('city'), 'trim|required');
        $this->form_validation->set_rules('email', dt_translate('email'), 'trim|required');
        $this->form_validation->set_rules('amount', dt_translate('last_name'), 'trim|required');
        $this->form_validation->set_rules('category_id', dt_translate('department'), 'trim|required');

        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        if ($this->form_validation->run() == false) {
            if ($id > 0) {
                $this->update_donation();
            } else {
                $this->add_donation();
            }
        } else {
            $data['first_name'] = $this->input->post('first_name', true);
            $data['last_name'] = $this->input->post('last_name', true);
            $data['city'] = $this->input->post('city', true);
            $data['email'] = $this->input->post('email', true);
            $data['phone'] = $this->input->post('phone', true);
            $data['amount'] = $this->input->post('amount', true);
            $data['category_id'] = $this->input->post('category_id', true);
            $data['type'] = $this->input->post('type', true);
            $data['cheque_no'] = $this->input->post('cheque_no', true);

            if ($id > 0) {
                $this->model_customer->update('app_donation', $data, "id=" . $id);

                $this->session->set_flashdata('msg', dt_translate('record_update'));
                $this->session->set_flashdata('msg_class', 'success');
                redirect('admin/donation', 'redirect');
            } else {

                $data['created_by'] = $admin_id;
                $data['payment_status'] ='success';
                $data['created_on'] = date("Y-m-d H:i:s");
                $donation_id=$this->model_customer->insert('app_donation', $data);

                if ($donation_id>0){

                    //Fetch Setting
                    $site_setting=$this->db->get('app_site_setting')->row_array();

                    //Fetch Donation
                    $this->db->select('app_donation.*,app_donation_category.title as category_title');
                    $this->db->where('app_donation.id',$donation_id);
                    $this->db->join('app_donation_category', 'app_donation_category.id=app_donation.category_id');
                    $donation=$this->db->get('app_donation')->row_array();

                    $dompdf = new Dompdf();
                    $site_setting['logo']=$this->imageToBase64(dt_get_CompanyLogo());
                    $site_setting['donation']=$donation;

                    $html = $this->load->view('admin/print/one', $site_setting,true);
                    $dompdf->loadHtml($html);
                    $dompdf->render();

                    $output = $dompdf->output();
                    $uploadPath = dirname(BASEPATH) . "/" . uploads_path;
                    $filename=$uploadPath."/donation_receipt/"."donation_receipt_".$donation_id.".pdf";

                    @file_put_contents($filename, $output);

                    $pdf_path=FCPATH.uploads_path."/donation_receipt/"."donation_receipt_".$donation_id.".pdf";

                    if (file_exists($pdf_path)){
                        //Send email
                        $subject = dt_get_CompanyName()." | ".dt_translate('donation');
                        $define_param['to_name'] = $data['first_name']." ".$data['last_name'];
                        $define_param['to_email'] =$data['email'];

                        $parameter['NAME'] = $data['first_name']." ".$data['last_name'];
                        $parameter['AMOUNT'] =$data['amount'];

                        $html = $this->load->view("email_template/donation", $parameter, true);
                        $this->sendmail->send($define_param, $subject, $html,$pdf_path);
                    }
                }

                $this->session->set_flashdata('msg', dt_translate('record_insert'));
                $this->session->set_flashdata('msg_class', 'success');
                redirect('admin/donation', 'redirect');
            }
        }
    }


    private function imageToBase64($path) {
        $path = $path;
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        return $base64;
    }

    //delete an admin
    public function delete_donation($id) {
        $id = (int) $id;
        if ($id > 0) {
            $this->model_customer->delete('app_donation', 'id=' . $id);
            $this->session->set_flashdata('msg', dt_translate('record_delete'));
            $this->session->set_flashdata('msg_class', 'success');
            echo true;
        } else {
            echo FALSE;
        }
    }

    public function donation_receipt($id){

        $dep_join = array(
            array(
                'table' => 'app_donation_category',
                'condition' => 'app_donation_category.id=app_donation.category_id',
                'jointype' => 'inner'
            ),
            array(
                'table' => 'app_admin',
                'condition' => 'app_admin.id=app_donation.created_by',
                'jointype' => 'inner'
            )
        );

        $app_donation = $this->model_customer->getData("app_donation", "app_donation.*,app_donation_category.title,app_admin.first_name as created_first_name,app_admin.last_name as created_last_name", "app_donation.id=".$id, $dep_join);

        if(isset($app_donation) && count($app_donation)>0){
            $app_donation_rec=$app_donation[0];

            $data['donation_data']=$app_donation_rec;
            $this->load->view('admin/receipt/donation', $data);
        }else{
            redirect('admin/donation');
        }
    }

    public function donation_export(){

        $admin_id = $this->session->userdata("ADMIN_ID");
        $order = "app_donation.created_on DESC";

        $dep_join = array(
            array(
                'table' => 'app_donation_category',
                'condition' => 'app_donation_category.id=app_donation.category_id',
                'jointype' => 'inner'
            )
        );
        $condition="";
        if($this->session->userdata("TYPE")=="A"){
            $condition.=" payment_status='success' ";
        }else{
            $condition.=" payment_status='success' AND created_by=".$admin_id;
        }

        $app_donation = $this->model_customer->getData("app_donation", "app_donation.*,app_donation_category.title", $condition, $dep_join, $order);

        if(isset($app_donation) && count($app_donation)){
            $filename="donation_".date('Y_m_d').".csv";
            $delimiter = ",";

            //create a file pointer
            $f = fopen('php://memory', 'w');

            //set column headers

            $fields = array(
                '#',
                dt_translate('first_name'),
                dt_translate('last_name'),
                dt_translate('email'),
                dt_translate('phone'),
                dt_translate('city'),
                dt_translate('amount'),
                dt_translate('payment_by'),
                dt_translate('cheque'),
                dt_translate('department'),
            );

            fputcsv($f, $fields, $delimiter);

            //output each row of the data, format line as csv and write to file pointer
            foreach ($app_donation as $donation){

                $lineData = array(
                    $donation['id'],
                    $donation['first_name'],
                    $donation['last_name'],
                    $donation['email'],
                    $donation['phone'],
                    $donation['city'],
                    number_format($donation['amount'],2),
                    $donation['type'],
                    $donation['cheque_no'],
                    $donation['title'],
                );

                fputcsv($f, $lineData, $delimiter);
            }

            //move back to beginning of file
            fseek($f, 0);

            //set headers to download file rather than displayed
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="' . $filename . '";');

            //output all remaining data on a file pointer
            fpassthru($f);
        }else{
            redirect('admin/donation');
        }
    }

    public function resend_donation_receipt(){
        $donation_id=$this->input->post('id', true);
        //Fetch Donation
        $this->db->select('app_donation.*,app_donation_category.title as category_title');
        $this->db->where('app_donation.id',$donation_id);
        $this->db->join('app_donation_category', 'app_donation_category.id=app_donation.category_id');
        $donation=$this->db->get('app_donation')->row_array();
        echo $this->load->view('admin/donation/resend', $donation,true);
    }

    public function send_resend_donation_receipt(){
        $email=$this->input->post('email', true);
        $donation_id=$this->input->post('id', true);

        //Fetch Donation
        $this->db->select('app_donation.*,app_donation_category.title as category_title');
        $this->db->where('app_donation.id',$donation_id);
        $this->db->join('app_donation_category', 'app_donation_category.id=app_donation.category_id');
        $data=$this->db->get('app_donation')->row_array();

        if (isset($data) && $data!=null){
            $pdf_path=FCPATH.uploads_path."/donation_receipt/"."donation_receipt_".$donation_id.".pdf";

            if (file_exists($pdf_path)){
                //Send email
                $subject = dt_get_CompanyName()." | ".dt_translate('donation');
                $define_param['to_name'] = $data['first_name']." ".$data['last_name'];
                $define_param['to_email'] =$email;

                $parameter['NAME'] = $data['first_name']." ".$data['last_name'];
                $parameter['AMOUNT'] =$data['amount'];

                $html = $this->load->view("email_template/donation", $parameter, true);
                $this->sendmail->send($define_param, $subject, $html,$pdf_path);

                $this->session->set_flashdata('msg',"Receipt has been sent.");
                $this->session->set_flashdata('msg_class', 'success');
                redirect('admin/donation', 'redirect');
            }
        }
    }
}
