<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Expense extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('model_admin');
        $this->lang->load('basic', dt_get_Langauge());
        $item_donation=is_module_enabled('expense');
        if($item_donation==false){
            redirect('admin/dashboard');
        }
    }

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


        $exp_join = array(
            array(
                'table' => 'app_expense_category',
                'condition' => 'app_expense_category.id=app_expense.category_id',
                'jointype' => 'inner'
            )
        );

        $condition="";
        if($this->session->userdata("TYPE")!="A"){
            $condition.=" app_expense.created_by=".$admin_id;
        }

        $expense = $this->model_admin->getData("app_expense", "app_expense.*,app_expense_category.title as category_title",$condition, $exp_join, $order);

        $data['expense_data'] = $expense;
        $this->load->view('admin/expense/index', $data);
    }

    public function add_expense() {
        $data['app_expense_category'] = $this->model_admin->getData('app_expense_category', '*', "status='A'");
        $data['title'] = dt_translate('add') . " " . dt_translate('expense');
        $this->load->view('admin/expense/add_update', $data);
    }

    public function update_expense($id) {

        $id = (int) $id;
        if ($id > 0) {
            $data['app_expense_category'] = $this->model_admin->getData('app_expense_category', '*', "status='A'");
            $expense_data = $this->model_admin->getData('app_expense', '*', "id='$id'");
            if (isset($expense_data) && count($expense_data) > 0) {
                $data['expense_data'] = $expense_data[0];
                $data['title'] = dt_translate('update') . " " . dt_translate('expense');
                $this->load->view('admin/expense/add_update', $data);
            } else {
                $this->session->set_flashdata('msg', dt_translate('invalid_request'));
                $this->session->set_flashdata('msg_class', 'failure');
                redirect('admin/expense');
            }
        } else {
            redirect('admin/expense');
        }
    }

    public function save_expense() {
        $admin_id = $this->session->userdata("ADMIN_ID");
        $id = (int) $this->input->post('id', TRUE);
        $this->form_validation->set_rules('amount', dt_translate('amount'), 'trim|required');
        $this->form_validation->set_rules('details', dt_translate('details'), 'trim|required');
        $this->form_validation->set_rules('category_id', dt_translate('expense_category'), 'trim|required');
        $this->form_validation->set_rules('expense_date', dt_translate('date'), 'trim|required');
        $this->form_validation->set_error_delimiters("<div class='error'>", "</div>");
        if ($this->form_validation->run() == FALSE) {
            $this->add_expense();
        } else {

            $data = array(
                'amount' => $this->input->post('amount', TRUE),
                'details' => $this->input->post("details", TRUE),
                'category_id'=>$this->input->post("category_id", TRUE),
                'expense_date'=>$this->input->post("expense_date", TRUE),
                'created_by'=>$admin_id,
            );

            if (isset($_FILES['expense_receipt']) && $_FILES['expense_receipt']['name'] != '') {

                $uploadPath = dirname(BASEPATH) . "/" . uploads_path;
                $fevicon_tmp_name = $_FILES["expense_receipt"]["tmp_name"];
                $fevicon_temp = explode(".", $_FILES["expense_receipt"]["name"]);
                $fevicon_name = time().uniqid();
                $new_fevicon_name = $fevicon_name . '.' . end($fevicon_temp);
                move_uploaded_file($fevicon_tmp_name, "$uploadPath/$new_fevicon_name");
                $data['expense_receipt'] = $new_fevicon_name;

                $old_image=$this->input->post('old_image');
                if(isset($old_image) && $old_image!=""){
                    if (file_exists(FCPATH.uploads_path."/".$old_image)){
                        @unlink(FCPATH.uploads_path."/".$old_image);
                    }
                }

            }

            if ($id > 0) {
                $this->model_admin->update('app_expense', $data, "id = '$id'");
                $this->session->set_flashdata("msg", dt_translate('record_update'));
                $this->session->set_flashdata("msg_class", "success");
                redirect('admin/expense');
            } else {
                $data['created_on'] = date('Y-m-d H:i:s');
                $this->model_admin->insert('app_expense', $data);
                $this->session->set_flashdata("msg", dt_translate('record_update'));
                $this->session->set_flashdata("msg_class", "success");
                redirect('admin/expense');
            }
        }
    }

    //delete expense
    public function delete_expense($id) {
        $id = (int) $id;
        if ($id > 0) {
            $this->model_admin->delete('app_expense', 'id=' . $id);
            $this->session->set_flashdata('msg', dt_translate('record_delete'));
            $this->session->set_flashdata('msg_class', 'success');
        } else {
            echo FALSE;
        }
    }

    //show deparment list
    public function expense_category() {
        $data['title'] = dt_translate('manage') . " " . dt_translate('expense');
        $order = "created_on DESC";
        $app_expense_category = $this->model_admin->getData("app_expense_category", "*", "", "", $order);
        $data['app_expense_category'] = $app_expense_category;
        $this->load->view('admin/expense_category/index', $data);
    }

    public function add_expense_category() {
        $data['title'] = dt_translate('add') . " " . dt_translate('expense');
        $this->load->view('admin/expense_category/add_update', $data);
    }

    public function update_expense_category($id) {

        $id = (int) $id;
        if ($id > 0) {

            $expense_data = $this->model_admin->getData('app_expense_category', '*', "id='$id'");
            if (isset($expense_data) && count($expense_data) > 0) {
                $data['expense_category_data'] = $expense_data[0];
                $data['title'] = dt_translate('update') . " " . dt_translate('expense');
                $this->load->view('admin/expense_category/add_update', $data);
            } else {
                $this->session->set_flashdata('msg', dt_translate('invalid_request'));
                $this->session->set_flashdata('msg_class', 'failure');
                redirect('admin/expense-category');
            }
        } else {
            redirect('admin/expense-category');
        }
    }

    public function save_expense_category() {

        $id = (int) $this->input->post('id', TRUE);
        $this->form_validation->set_rules('title', dt_translate('title'), 'trim|required|is_unique[app_expense_category.title.id.' . $id . ']');
        $this->form_validation->set_rules('status', dt_translate('status'), 'trim|required');
        $this->form_validation->set_error_delimiters("<div class='error'>", "</div>");
        if ($this->form_validation->run() == FALSE) {
            if($id>0){
                $this->update_expense_category($id);
            }else{
                $this->add_expense_category();
            }

        } else {

            $data = array(
                'title' => $this->input->post('title', TRUE),
                'status' => $this->input->post("status", TRUE)
            );
            if ($id > 0) {
                $this->model_admin->update('app_expense_category', $data, "id = '$id'");
                $this->session->set_flashdata("msg", dt_translate('record_update'));
                $this->session->set_flashdata("msg_class", "success");
                redirect('admin/expense-category');
            } else {
                $data['created_on'] = date('Y-m-d H:i:s');
                $this->model_admin->insert('app_expense_category', $data);
                $this->session->set_flashdata("msg", dt_translate('record_update'));
                $this->session->set_flashdata("msg_class", "success");
                redirect('admin/expense-category');
            }
        }
    }

    //delete expense
    public function delete_expense_category($id) {
        $id = (int) $id;
        if ($id > 0) {
            $app_expense = $this->model_admin->getData('app_expense', 'id', "category_id='$id'");
            if(count($app_expense)>0){
                $this->session->set_flashdata('msg', dt_translate('delete_already_used'));
                $this->session->set_flashdata('msg_class', 'failure');
            }else{
                $this->model_admin->delete('app_expense_category', 'id=' . $id);
                $this->session->set_flashdata('msg', dt_translate('record_delete'));
                $this->session->set_flashdata('msg_class', 'success');
            }
        } else {
            echo FALSE;
        }
    }


    public function expense_export(){
        $admin_id = $this->session->userdata("ADMIN_ID");
        $order = "app_expense.created_on DESC";
        $exp_join = array(
            array(
                'table' => 'app_expense_category',
                'condition' => 'app_expense_category.id=app_expense.category_id',
                'jointype' => 'inner'
            )
        );

        $condition="";
        if($this->session->userdata("TYPE")!="A"){
            $condition.=" app_expense.created_by=".$admin_id;
        }

        $expense = $this->model_admin->getData("app_expense", "app_expense.*,app_expense_category.title as category_title",$condition, $exp_join, $order);

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

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

            //set column headers

            $fields = array(
                '#',
                dt_translate('expense_category'),
                dt_translate('amount'),
                dt_translate('details'),
                dt_translate('date')
            );

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

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

                $lineData = array(
                    $expense_data['id'],
                    $expense_data['category_title'],
                    number_format($expense_data['amount'],2),
                    $expense_data['details'],
                    get_formated_date($expense_data['expense_date'],"N")
                );

                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/expense');
        }
    }
}

?>