<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ACCAjax
 *
 * @author Ola
 */
class TicketingAjax extends mainController
{

    private $year_id;
    private $year_id_actual;
    private $db;

    public function __construct()
    {
        parent::__construct();
        $this->year_id = Session::getCurrentYearID();
        $this->year_id_actual = Session::getCurrentYearIDActual();
        $this->db = DBConnectorFactory::loadDriver();
        $this->controller_permission = Session::getPermissionsObject();

        $this->load->model('Ticketing');
    }

    public function landing()
    {
    }
    public function ticketing_type_list()
    {
        $columns = array(
            'ticketing_type_name',
            array(
                'db' => 'ticketing_type_id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "data-target" => "#ticketing_type_modal",
                                    "permission" => "edit_ticketing_type"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_ticketing_type"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "ticketing_type_id";
        $table = "tbl_ticketing_type";
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function maintenance_type_list()
    {
        $columns = array(
            'maintenance_type_name',
            array(
                'db' => 'maintenance_type_id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "data-target" => "#ticketing_type_modal",
                                    "permission" => "edit_maintenance_type"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_maintenance_type"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "maintenance_type_id";
        $table = "tbl_maintenance_type";
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function submit_ticketing_type()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_ticketing_type();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function submit_maintenance_type()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_maintenance_type();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function delete_ticketing_type()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_ticketing_type();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function delete_maintenance_type()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_maintenance_type();
        die(empty($submit) ? "ok" : $submit[0]);
    }

    public function ticketing_station_list()
    {
        $columns = array(
            'ticketing_station_name', 'ticketing_station_location', 'Depot_Name',
            array(
                'db' => 'ticketing_station_id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "data-target" => "#ticketing_station_modal",
                                    "permission" => "edit_station"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_station"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "ticketing_station_id";
        $table = "ticketing_station_list";
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function maintenance_supporter_list()
    {
        $columns = array(
            'maintenance_supporter_name',
            array(
                'db' => 'maintenance_supporter_id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "data-target" => "#ticketing_station_modal",
                                    "permission" => "edit_maintenance_supporter"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_maintenance_supporter"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "maintenance_supporter_id";
        $table = "tbl_maintenance_supporter";
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function submit_ticketing_station()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_ticketing_station();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_maintenance_supporter()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_maintenance_supporter();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function delete_ticketing_station()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_ticketing_station();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function delete_maintenance_supporter()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_maintenance_supporter();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function maintenanceSearch()
    {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->ticketing_class->setData($_GET)->maintenanceSearch($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }
    public function maintenanceInvoiceSearch()
    {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->ticketing_class->setData($_GET)->maintenanceInvoiceSearch($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }
    public function maintenanceSupporterSearch()
    {
        $term = isset($_GET['term']) ? $_GET['term'] : null;
        $page = isset($_GET['page']) ? $_GET['page'] - 1 : 0;
        $ALL = $this->_registry->ticketing_class->setData($_GET)->maintenanceSupporterSearch($term, $page, $_GET['limit']);
        echo json_encode(array('data' => $ALL['data'], 'is_more' => $ALL['is_more']));
    }

    public function ticketing_list()
    {
        $cond = '';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and ticketing_date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '"';
        if (is_numeric($_GET['customer_id']))
            $cond .= ' and customer_id ="' . $_GET['customer_id'] . '"';
        $columns = array(
            'ticketing_nb', 'Customer_Name', 'ticketing_type_name', 'ticketing_date', 'ticketing_status_name',
            array(
                'db' => 'ticketing_status_id',
                'formatter' => function ($d, $row) {
                    if ($d == 3) {
                        $start_date = strtotime($row['date_created']);
                        $end_date = strtotime($row['date_finished']);
                    } else {
                        $start_date = strtotime(date("Y-m-d H:i:s"));
                        $end_date = strtotime($row['date_created']);
                    }
                    $duration = abs($end_date - $start_date) / (60 * 60);
                    return '<span class="label text-white" style="background-color:' . ($d == 3 ? '#868083' : ($duration < 6 ? '#49CA09' : (($duration >= 6 && $duration < 9) ? '#FBF700' : (($duration >= 9 && $duration < 12) ? '#FB7A00' : '#FB0000')))) . '">' . CommonFunctions::formatNumber(abs($end_date - $start_date) / (60 * 60)) . ' Hour(s)</span>';
                }
            ),
            array(
                'db' => 'ticketing_id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "href" => "Ticketing/ticketing/{$d}",
                                    "permission" => "edit_ticketing"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_ticketing"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            ), 'date_created', 'date_finished'
        );
        $key = "ticketing_id";
        $table = "ticketing_list";
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }
    public function event_list()
    {
        $cond = '';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and from_date = "' . $_GET['from_date'] . '" and to_date= "' . $_GET['to_date'] . '"';

        $columns = array(
            'event_id', 'event_name', 'from_date', 'to_date', 'from_time', 'to_time', 'event_date',

            array(
                'db' => 'id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("View"),
                                    "class" => "edit hidden",
                                    "icon" => "fa-pencil",
                                    "href" => "Ticketing/View_maintenance/{$d}",
                                    "permission" => "view_maintenance"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "href" => "Ticketing/add_event/{$d}",
                                    "permission" => "edit_event"
                                ],

                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_maintenance"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "id";
        $table = "tbl_event";
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }
    public function appointment_list()
    {
        $cond = '';
        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and app_date between  "' . $_GET['from_date'] . '" and  "' . $_GET['to_date'] . '"';

        $columns = array(
            'id', 'Customer_Name','event_name', 'app_date', 'app_time',

            array(
                'db' => 'id',
                'formatter' => function ($d) {
                    $html = Forms::action_snippet(
                        [
                            "color" => "complete",
                            "isDropDown" => true,
                            "data_id" => $d,
                            "ActionOption" => [
                                [
                                    "title" => CommonLanguage::getMessage("View"),
                                    "class" => "edit hidden",
                                    "icon" => "fa-pencil",
                                    "href" => "Ticketing/View_maintenance/{$d}",
                                    "permission" => "view_maintenance"
                                ],
                                [
                                    "title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "href" => "Ticketing/add_appointment/{$d}",
                                    "permission" => "edit_event"
                                ],

                                [
                                    "title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_maintenance"
                                ]
                            ]
                        ]
                    );
                    return $html;
                }
            )
        );
        $key = "id";
        $table = "(SELECT
        `tbl_appointment`.`ID` as id,
        `tbl_event`.`event_name`,
        `tbl_appointment`.`app_date`,
        `tbl_appointment`.`app_time`,
        `tbl_customers`.`Customer_Name`
    FROM
        `tbl_event`,
        `tbl_appointment`,
        `tbl_customers`
    WHERE
        `tbl_event`.`id` = `tbl_appointment`.`event_id` AND `tbl_customers`.`Customer_ID` = `tbl_appointment`.`customer_id`
    ORDER BY
        `tbl_appointment`.`app_date`
    DESC
        ) as appointment";
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $cond);
        echo json_encode($data);
    }
    public function print_maintenance()
    {
        $data = $this->_registry->ticketing_class->get_maintenance_data($_GET['maintenance_id']);
        $data['Customer_Name'] = $data['main']['Customer_Name'];
        $data['Customer_Phone'] = $data['main']['Customer_Phone'];
        $data['phone_brand'] = $data['main']['phone_brand'];
        $data['maintenance_type_name'] = $data['main']['maintenance_type_name'];
        $data['color'] = $data['main']['color'];

        $data['password'] = $data['main']['password'];
        $data['User_Name'] = $data['main']['User_Name'];

        $data['color'] = $data['main']['color_name'];
        $data['type_name'] = $data['main']['type_name'];
        $data['other_note'] = $data['main']['other_note'];

        $data['date_created'] = $data['main']['date_created'];
        $data['serial_number'] = $data['main']['serial_number'];
        $data['image'] =  'org_logo/invoice_logo.jpg';

        $data['ExchangeRate'] =   $data['main']['exchange_rate'];
        $data['maintenance_id'] =   $data['main']['maintenance_id'];
        $data['range_cost'] =   $data['main']['range_cost'];


         $template_row = Forms::build_print_template('maintenance_view', $data);
        $html = $template_row['html'];
        die($html);
    }

    public function maintenance_list() {
        $cond = '';
        if(!$this->controller_permission->hasPermission('view_all_maintenance')){
           $Employee_ID = smc_session()['user_details']['User_ID'];
            $cond .= ' and Employee_ID ="' . $Employee_ID . '"';

        }else if (isset($_GET['supporter_id']) && is_numeric($_GET['supporter_id'])){
            $cond .= ' and Employee_ID ="' . $_GET['supporter_id'] . '"';
        }

        if (!empty($_GET['from_date']) && !empty($_GET['to_date']))
            $cond .= ' and maintenance_date between "' . $_GET['from_date'] . '" and "' . $_GET['to_date'] . '"';

        if (isset($_GET['customer_id']) && is_numeric($_GET['customer_id']))
            $cond .= ' and customer_id ="' . $_GET['customer_id'] . '"';

        if (isset($_GET['ticketing_status_id']) && is_numeric($_GET['ticketing_status_id']))
            $cond .= ' and maintenance_status_id ="' . $_GET['ticketing_status_id'] . '"';

        
        if (isset($_GET['type_id']) && is_numeric($_GET['type_id']))
            $cond .= ' and type_id ="' . $_GET['type_id'] . '"';


        if (!empty($_GET['serial_number']))
            if (is_numeric($_GET['serial_number']))
                $cond .= ' and serial_number = "' . $_GET['serial_number'] . '"';
        if (!empty($_GET['invoice_number']))
            if (is_numeric($_GET['invoice_number']))
                $cond .= ' and invoice_number = "' . $_GET['invoice_number'] . '"';

        $columns = array('maintenance_id','Customer_Name','brand_name','maintenance_note','serial_number',
            array('db' => 'invoice_number', "formatter" => function($d, $row) {
                if(!empty($row['invoice_number'])){
                $invoice_class = new Invoice();
                $inv_arr = $invoice_class->getInvoiceByID($row['invoice_number']);
                    return $inv_arr['Main']['ID'];
                }else{
                    return '';

                }
                })
                ,'Employee_full_name','maintenance_type_name','maintenance_date',array('db' => 'ticketing_status_name',
        'formatter' => function( $d , $row ) {
            
         $option_arr = [
             ["title" => $d,
                      "class" => "$d",
             ]
         ];
        
         $html = Forms::action_snippet(["color" => "complete", "isDropDown" => false, "data_id" =>$d,
         "ActionOption" => $option_arr]);
            return $html;
        }
       ),
        array('db' => 'nonce',
        'formatter' => function( $d , $row ) {
            
         $option_arr = [
             ["title" => CommonLanguage::getMessage("play"),
                      "class" => "voice_download",
                      "icon" => "fa-pencil",
                      "permission" => "maintenance_list"
             ]
         ];
        
         $html = Forms::action_snippet(["color" => "complete", "isDropDown" => false, "data_id" =>$d,
         "ActionOption" => $option_arr]);
            return $html;
        }
       ),
                         array('db' => 'maintenance_id',
                               'formatter' => function( $d , $row ) {
                                   
                                $option_arr = [
                                    ["title" => CommonLanguage::getMessage("View"),
                                             "class" => "edit",
                                             "icon" => "fa-pencil",
                                             
                                             "href"=>"Ticketing/View_maintenance/{$d}",
                                             "permission" => "view_maintenance"
                                    ]
                                ];
                                if($row['maintenance_status_id'] != 4 || $this->controller_permission->hasPermission('enable_maintenance_controller')){
                                    $option_arr[] =  ["title" => CommonLanguage::getMessage("Finish"),
                                    "class" => "finish_maintenance",
                                    "icon" => "fa-pencil",
                                    "permission" => "finish_maintenance"
                                    ];
                                    $option_arr[] =  ["title" => CommonLanguage::getMessage("Edit"),
                                    "class" => "edit",
                                    "icon" => "fa-pencil",
                                    "href"=>"Ticketing/add_maintenance/{$d}",
                                    "permission" => "edit_maintenance"
                                    ];
                                    $option_arr[] =  ["title" => CommonLanguage::getMessage("Delete"),
                                    "class" => "delete",
                                    "icon" => "fa-trash",
                                    "permission" => "delete_maintenance"
                                    ];
                                }
                                $option_arr[] =  ["title" => CommonLanguage::getMessage("print"),
                                "class" => "print_maintenance",
                                "icon" => "fa-print"
                                ];
                                
                                if (empty($row['invoice_number'])) {

                                    $option_arr[] =   ["title" => CommonLanguage::getMessage("start_maintenance"),
                                    "class" => "invoice",
                                    "icon" => "fa-pencil",
                                    "href"=>"Ticketing/addpurchase/sales/M{$d}",
                                    "permission" => "maintenance_sales_invoice"
                                    ];
                                }

                                if (!empty($row['invoice_number'])) {
                                    $option_arr[] =   ["title" => CommonLanguage::getMessage("edit_invoice_maintenance"),
                                    "class" => "edit invoice",
                                    "icon" => "fa-pencil",
                                    "href"=>"Ticketing/addpurchase/sales/".$row['invoice_number']."/M{$d}",
                                    "permission" => "maintenance_sales_invoice_edit"
                                    ];
                                }
                                $html = Forms::action_snippet(["color" => "complete", "isDropDown" => true, "data_id" =>$d,
                                "ActionOption" => $option_arr]);
                                   return $html;
                               }
                              ),'date_created','date_finished','invoice_number','nonce','maintenance_status_id'
                        );
        $key = "maintenance_id";
        $table = "maintenance_list";
        $data = DataTable::complex($_GET, $table, $key, $columns,' 1=1 '.$cond);
         echo json_encode($data);
    }
    public function submit_ticketing()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_ticketing();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_maintenance()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_maintenance();
        die(json_encode(is_numeric($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success',$submit] : [$submit[0], 'danger']));
    }
    public function submit_event()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_event();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function submit_appointment()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_appointment();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function delete_ticketing()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_ticketing();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function delete_maintenance()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_maintenance();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function delete_event()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_event();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function delete_appointment()
    {
        $submit = $this->_registry->ticketing_class->setData($_GET)->delete_appointment();
        die(empty($submit) ? "ok" : $submit[0]);
    }
    public function get_ticketing_calendar()
    {
        $data = $this->_registry->ticketing_class->setData($_GET)->get_ticketing_calendar();
        die(json_encode($data));
    }

    public function get_ticketing_reply()
    {
        $data = $this->_registry->ticketing_class->get_ticketing_reply($_GET['ticketing_reply_id']);
        die(json_encode($data));
    }
    public function get_maintenance_reply()
    {
        $data = $this->_registry->ticketing_class->get_maintenance_reply($_GET['ticketing_reply_id']);
        die(json_encode($data));
    }
    public function submit_ticketing_reply()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_ticketing_reply();
        die(json_encode(is_numeric($submit[0]) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success', $this->_registry->ticketing_class->get_ticketing_reply($submit[0], false)] : [$submit[0], 'danger']));
    }
    public function submit_maintenance_reply()
    {
        $submit = $this->_registry->ticketing_class->setData($_POST)->submit_maintenance_reply();
        die(json_encode(is_numeric($submit[0]) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success', $this->_registry->ticketing_class->get_ticketing_reply($submit[0], false)] : [$submit[0], 'danger']));
    }
    public function get_event()
    {
        $data =  $this->_registry->ticketing_class->setData($_GET)->get_event();
        die(json_encode($data));
     }
     public function save_audio() {
        $submit = $this->_registry->ticketing_class->setData($_POST)->save_audio();
        die(json_encode([$submit]));
    }
    public function finish_maintenance()
    {
        $data = $this->_registry->ticketing_class->finish_maintenance($_GET['maintenance_id']);


        die($data);
    }

}
