<?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 GarageAjax
 *
 * @author Ola
 */
class GarageAjax extends mainController {

    public function __construct() {
        parent::__construct();
        $this->load->model('Garage');
    }

    public function landing() {

    }

    public function DailyCheckupListRequest() {
        $cond = '';
        if (isset($_GET['Checkup_Date'])) {
            $cond = ' Chekup_Date = "' . smc_escape($_GET['Checkup_Date']) . '"';
        }
        $columns = array(
            array('db' => 'Vehicle_Registration_Number', 'dt' => 0),
            array('db' => 'Vehicle_Type_Name', 'dt' => 1),
            array('db' => 'In_Milage', 'dt' => 2),
            array('db' => 'Out_Milage', 'dt' => 3),
            array('db' => 'Distance', 'dt' => 4),
            array('db' => 'Fuel', 'dt' => 5)
        );
        $key = 'Vehicle_Registration_Number';
        $table = 'checkup_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function VehicleListRequest() {
        $columns = array('Vehicle_Type_Name','Vehicle_Name','Vehicle_Registration_Number','Model_Name','driver_name',
                         'Vehicle_Oil_Change','last_mecanique_year','last_syndicate_date',
                        array("db" => "is_disabled",  "formatter" => function($d, $row) {
                        $Statuses = [   CommonLanguage::getMessage('enabled')."#label-info",CommonLanguage::getMessage('disabled')."#label-danger"];
                        return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
                    }),
                         array('db' => 'Vehicle_ID',
                               "formatter" => function($d,$row) {
                                $option_arr = [["title" => CommonLanguage::getMessage("Edit"),
                                                "class" => "openFrame",
                                                "icon" => "fa-pencil",
                                                "attr"  => "data-src='Garage/ViewVehicle/{$d}?is_pop=1&modal=1'",
                                                "permission"=>"edit_vehicle"
                                               ],
                                               ["title" => CommonLanguage::getMessage("copy"),
                                                "class" => "copy_row",
                                                "icon" => "fa-copy",
                                                "attr"  => "data-id='{$d}'",
                                                "data-target"=>"#EditVehicle",
                                                "permission"=>"copy_vehicle"
                                               ],
                                               ["title" => CommonLanguage::getMessage("view"),
                                                "class" => "View",
                                                "icon" => "fa-eye",
                                                "href" => "Garage/ViewVehicle/{$d}",
                                                "permission"=>"ViewVehicle"
                                               ]];
                                            if($row['is_disabled']==1){
                                                $option_arr[] = 
                                                    ["title" => CommonLanguage::getMessage("enable"),
                                                     "class" => "enable_disable_vehicle",
                                                     "icon" => "fa-check",
                                                     "attr"=>"data-status='0'",
                                                     "permission" => "enable_disable_vehicle"]; 
                                            }else{
                                                $option_arr[] = 
                                                    ["title" => CommonLanguage::getMessage("disable"),
                                                     "class" => "enable_disable_vehicle",
                                                     "icon" => "fa-times",
                                                     "attr"=>"data-status='1'",
                                                     "permission" => "enable_disable_vehicle"]; 
                                            }
                                   $html = Forms::action_snippet(["color" => "success-darker", "isDropDown" => true,
                                       "data_id"=>$d,
                                                                  "ActionOption" => $option_arr]);
                                   return $html;
                               })
                        );
        $key = 'Vehicle_ID';
        $table = 'vehicle_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function VehicleDriverListRequest() {

        $columns = array(
            array('db' => 'Vehicle_Type_Name', 'dt' => 0),
            array('db' => 'Vehicle_Registration_Number', 'dt' => 1),
            array('db' => 'Vehicle_Oil_Change', 'dt' => 2),
            array('db' => 'Driver_Name', 'dt' => 3),
            array('db' => 'Sales_Man_Name', 'dt' => 4),
            array('db' => 'Zone_Name', 'dt' => 5),
            array('db' => 'ID', 'dt' => 6,
                  "formatter" => function($d, $row) {
                      $html = Forms::action_snippet(["color" => "success-darker", "isDropDown" => true, "data_id" => "{$d}/{$row[7]}",
                                                     "ActionOption" => [['title' => CommonLanguage::getMessage('delete'),
                                                                         'class' => 'Delete',
                                                                         'icon' => 'fa-trash'
                                                                        ],
                                                                        ['title' => CommonLanguage::getMessage('Edit'),
                                                                         'class' => 'UpdateVehcile',
                                                                         'icon' => 'fa-pencil',
                                                                         'data-target' => '#assignVehicleDriver'
                                                                        ]]]);
                      return $html;
                  }),
            array('db' => 'ID', 'dt' => 7)
        );
        $key = 'ID';
        $table = 'vehicle_driver_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function getVehicleCheckUpSetting() {
        $_GET['checkup_array'] = ['check_out', 'check_in', 'check_in_out'];
        $columns = array('checkup_setting_title',
                         array('db' => 'checkup_setting_type', 'dt' => 1,
                               "formatter" => function($d) {
                                   return CommonLanguage::getMessage($_GET['checkup_array'][$d]);
                               }),
                         array('db' => 'checkup_setting_id', 'dt' => 2,
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(["color" => "success-darker",
                                                                  "isDropDown" => false,
                                                                  "data_id" => "{$d}/{$row[1]}",
                                                                  "ActionOption" => [
                                                                      ['title' => '',
                                                                       'class' => 'edit_checkup_setting',
                                                                       'data-target' => '#checkup-setting-modal',
                                                                       'icon' => 'fa-pencil'
                                                                      ]]]);
                                   return $html;
                               })
                        );
        $key = 'checkup_setting_id';
        $table = 'tbl_garage_vehicle_checkup_setting';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }
    public function getRentType() {
        $columns = array('rent_type_name',
                         array('db' => 'rent_type_price', 'dt' => 1,
                               "formatter" => function($d, $row) {
                                   return CommonFunctions::formatNumber($d);
                               }),'Currency_Name',
                         array('db' => 'rent_type_id', 'dt' => 3,
                               "formatter" => function($d, $row) {
                                   $html = Forms::action_snippet(["color" => "success-darker",
                                                                  "isDropDown" => true,
                                                                  "data_id" => "{$d}",
                                                                  "ActionOption" => [
                                                                      ['title' =>CommonLanguage::getMessage('Edit'),
                                                                       'class' => 'edit_rent_type',
                                                                       'data-target' => '#add-edit-rent-type-modal',
                                                                       'attr'=>"data-id={$d}",
                                                                       'icon' => 'fa-pencil'
                                                                      ],
                                                                      ['title' => CommonLanguage::getMessage('delete'),
                                                                       'class' => 'delete_rent_type',
                                                                       'attr'=>"data-id={$d}",
                                                                       'icon' => 'fa-trash'
                                                                      ]]]);
                                   return $html;
                               })
                        );
        $key = 'rent_type_id';
        $table = 'rent_type_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function getCheckupList() {
        $columns = array('vehicle_name','veh_name', 'check_out_date',
                         array('db' => 'check_in', 
                               "formatter" => function($d, $row) {
                                   return $d == 1 ? '<i class="fa fa-check"></i>' : '<i class="fa fa-times"></i>';
                               }),
                         array('db' => 'check_in_date',
                               "formatter" => function($d, $row) {
                                   return $row['check_in'] == 1 ? $d : '<i class="fa fa-times"></i>';
                               }),
                         array('db' => 'vehicle_mileage_out',
                               "formatter" => function($d, $row) {
                                   return $row['check_in'] == 1 ? ($row['vehicle_mileage_in'] - $row['vehicle_mileage_out']) . ' ' . CommonLanguage::getMessage('km') : '<i class="fa fa-times"></i>';
                               }),
                         array('db' => 'Vehicle_Fuel_Consumption',
                               "formatter" => function($d, $row) {
                                   return $row['check_in'] == 1 ? ((($row['vehicle_mileage_in'] - $row['vehicle_mileage_out']) / 100) * $d) . ' ' . CommonLanguage::getMessage('L') : '<i class="fa fa-times"></i>';
                               }), 'vehicle_mileage_in'
                        );
        $key = 'Entry_ID';
        $table = 'check_up_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, !empty($_GET['Truck_ID']) ? ' and Vehicle_ID = "' . $_GET['Truck_ID'] . '"' : '');

        echo json_encode($data);
    }

    public function submitCheckupSetting() {
        $submit = $this->_registry->vehicle->setData($_POST)->submitCheckupSetting();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function EditVehicleAjax() {

        if (isset($_POST["Vehicle_Code"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            if ($_POST['Is_Edit']) {
                $RET = $this->_registry->vehicle->setData($_POST)->updateVehicle();
            } else {
                $RET = $this->_registry->vehicle->setData($_POST)->addVehicle();
            }


            die(json_encode(empty($RET) ? "OK" : $RET));
        }
    }

    //    public function vehicleCheckinCheckOut(){
    //        $checkup = $this->_registry->vehicle->setData($_POST)->insertVehicleCheckup();
    //        die(json_encode(empty($checkup) ? [CommonLanguage::getMessage('Submitted_Successfully'),"success"] : 
    //                        [($checkup[0] == 'you_have_check_out_before') ? CommonLanguage::getMessage($checkup[0]) : $checkup[0],"danger"])); 
    //    }
    public function vehicleCheckup() {
        $checkup = $this->_registry->vehicle->setData($_POST)->vehicleCheckup();
        die(json_encode(empty($checkup) ? [CommonLanguage::getMessage('Submitted_Successfully'), "success"] :
                        [$checkup[0], "danger"]));
    }

    //    public function TruckCheckupAjax() {
    //        if (isset($_POST["Vehicle_ID"])) {
    //            $counter = $this->_registry->vehicle->checkMaintenance($_POST['Vehicle_ID']);
    //            $new_counter = $_POST['Vehicle_Milage'] - $counter['Vehicle_Milage'] + $counter['Vehicle_Maintenance_Counter'];
    //
    //            if ($new_counter >= $counter['Vehicle_Maintenance_Period']) {
    //                $counter_val = $new_counter;
    //                $maintenance_status = 3;
    //                $_POST['New_Maintenance_Status'] = $maintenance_status;
    //                //        echo "Need for Maintenance";
    //            } else {
    //                $counter_val = $new_counter;
    //                $_POST['New_Maintenance_Status'] = $counter['Vehicle_Maintenance_Status'];
    //            }
    //            $_POST['New_Counter'] = $counter_val;
    //            $checkup = $this->_registry->vehicle->setData($_POST)->insertVehicleCheckup();
    //            die(empty($checkup) ? "OK" : "error");
    //        }
    //    }

    public function deleteVehicleAjax() {
        if (isset($_POST["GetID"])) { // to delete assign vehicle 
            $Vehicle_ID = $_POST["GetID"];
            $delete_assign = $this->_registry->vehicle->deleteAssignVehicle($Vehicle_ID);
            die(empty($delete_assign) ? "OK" : "error");
        }
    }

    public function assignVehicleDriverAjax() {
        if (isset($_GET["Usage_Type"])) {
            die(json_encode($this->_registry->vehicle->getVehicleCode($_GET["Usage_Type"])));
        }

        if (isset($_POST["Assign_Vehicle_Code"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);

            if (isset($_POST['Vehicle_Driver_ID'])) {
                $RET = $this->_registry->vehicle->setData($_POST)->updateVehicleDriver($_POST['Vehicle_Driver_ID']);
            } else {
                $RET = $this->_registry->vehicle->setData($_POST)->addVehicleDriver();
            }

            die(json_encode(empty($RET) ? "OK" : $RET));
        }
        if (isset($_GET['GetID'])) {
            $id = $_GET['GetID'];
            $result = $this->_registry->vehicle->getVehicleDriverToEdit($id);
            if ($result ? die(json_encode($result)) : "error")
                ;
        }
    }

    public function VehicleExpenseListRequest() {
        $cond = '';
        if (isset($_GET['from_date'])) {
            $from_date = empty($_GET['from_date']) ? date('Y-m-01') : $_GET['from_date'];
            $to_date = empty($_GET['to_date']) ? Date::getToday() : $_GET['to_date'];
            $cond = ' and Truck_Expense_Date between "' . smc_escape($from_date) . '" and "' . smc_escape($to_date) . '"';
        }
        if(!empty($_GET['vehicle_id'])){
            $expense_ids_array = $this->_registry->vehicle->getExpenseIdsLinkedVehicle($_GET['vehicle_id']);
            //            echo '<pre>';
            //            print_r($expense_ids_array);
            if(!empty($expense_ids_array))
                $cond .= ' and Truck_Expense_ID in ('.implode(",",$expense_ids_array).')';
            else
                $cond .= ' and 1=2';
        }

        $columns = array('vehicle_data', 'Truck_Expense_Description','Truck_Expense_Date',
                         array('db' => 'Expense_Amount', 'formatter' => function($d, $row) {
                             return CommonFunctions::public_round_number($d) . ' ' . CurrencyFactory::getCurrencySymbol($row['Currency_ID']);
                         }),
                         array('db' => 'Truck_Expense_ID', 'formatter' => function($d, $row) {
                             $html = Forms::action_snippet(["color" => "success-darker", 
                                                            "isDropDown" => true, 
                                                            "data_id" => $d,
                                                            "ActionOption" => [
                                                                ["title" => CommonLanguage::getMessage("Edit"),
                                                                 "class" => "Edit",
                                                                 "icon" => "fa-pencil",
                                                                 "permission" => "edit_truck_expense",
                                                                 "href" => "Garage/VehicleExpenses/" . ($row['Is_Hidden'] == 1 ? 'act/' : '') . "{$d}"
                                                                ],["title" => CommonLanguage::getMessage("delete"),
                                                                   "class" => "delete",
                                                                   "icon" => "fa-trash",
                                                                   "permission" => "delete_truck_expense"
                                                                  ]
                                                            ]]);
                             return $html;
                         }),'Currency_ID','Is_Hidden'
                        );
        $key = 'Truck_Expense_ID';
        $table = 'vehicle_expense_list';
        $data = DataTable::complex($_GET, $table, $key, $columns,' 1=1 '.$cond);

        echo json_encode($data);
    }

    public function VehicleMaintenanceRequest() {

        $columns = array(
            array('db' => 'Vehicle_Type_Name', 'dt' => 0),
            array('db' => 'Vehicle_Registration_Number', 'dt' => 1),
            array('db' => 'Vehicle_Milage', 'dt' => 2),
            array('db' => 'Vehicle_Maintenance_Counter', 'dt' => 3),
            array('db' => 'Vehicle_Maintenance_Period', 'dt' => 4),
            array('db' => 'Vehicle_Maintenance_Status', 'dt' => 5,
                  "formatter" => function($d) {
                      $Statuses = [$this->_registry->expenses->getStatusName(14) . "#label-info", $this->_registry->expenses->getStatusName(15) . "#label-warning", $this->_registry->expenses->getStatusName(16) . "#label-important"];

                      return '<span class="label ' . explode("#", $Statuses[$d - 1])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d - 1])[0] . '</span>';
                  }),
            array('db' => 'Vehicle_ID', 'dt' => 6,
                  "formatter" => function($d, $row) {
                      $Statuses = [$this->_registry->expenses->getStatusName(14) . "#label-info", $this->_registry->expenses->getStatusName(15) . "#label-warning", $this->_registry->expenses->getStatusName(16) . "#label-important"];

                      $html = "<div class='btn-group' >
                        <button type='button' class='btn btn-default  dropdown-toggle' data-toggle='dropdown' aria-expanded='false'  >
                            <i class='fa fa-pencil'> <span class='caret'></span></i>
                        </button><ul class='dropdown-menu Maintenance_Status' data-id='{$d}' role='menu' style='cursor:pointer' name='Vehicle_Maintenance_Status' >";
                      for ($x = 0; $x < count($Statuses) - 1; $x++) {
                          if ($row[5] - 1 != $x)
                              $html .= "<li value='" . ($x + 1) . "'><a href='#'>" . explode("#", $Statuses[$x])[0] . "</a></li>";
                      }
                      $html .= "</ul></div>";
                      return $html;
                  })
        );
        $key = 'Vehicle_ID';
        $table = 'vehicle_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);

        echo json_encode($data);
    }

    public function vehicleExpensesAjax() {
        if (isset($_POST["expense"])) {
            $insert = $this->_registry->vehicle->setData($_POST)->addTruckExpenses();
            die(empty($insert) ? "success" : $insert[0]);
        }
    }

    public function edit_vehicle_expense() {
        if (isset($_POST["expense"])) {
            $insert = $this->_registry->vehicle->setData($_POST)->edit_vehicle_expense();
            die(empty($insert) ? "success" : $insert[0]);
        }
    }

    public function VehicleMaintenanceAjax() {
        if (isset($_GET["Maintenance_Status"]) && isset($_GET["Vehicle_ID"])) { // to update Status
            $StatusUpdate = $this->_registry->vehicle->updateStatus(intval($_GET["Maintenance_Status"]), intval($_GET["Vehicle_ID"]));

            die(empty($StatusUpdate) ? "OK" : "error");
        }
    }

    public function getVehicleData() {
        $RET = $this->_registry->vehicle->setData($_GET)->getVehicleData();
        die(json_encode($RET));
    }

    public function getCheckupStatusData() {
        $RET = $this->_registry->vehicle->setData($_GET)->getCheckupStatusData();
        die(json_encode($RET));
    }

    public function vehicleWeighbridgeAjax() {
        $logged_id = Session::getUserID();
        array_push($_POST, $logged_id);
        $RET = $this->_registry->vehicle->setData($_POST)->addVehicleWeighbridge();

        die(empty($RET) ? "OK" : $RET[0]);
    }

    public function addVehicleColorAjax() {
        if (isset($_POST["ColorID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleColor();
            if (empty($RET)) {
                $vehicleColor = $this->_registry->vehicle->getLastOfType('tbl_color', 'Color_ID');
                die(json_encode(['OK', $vehicleColor]));
            } else {
                die(json_encode(['error', $vehicleColor]));
            }
        }
    }

    public function addVehicleFuelType() {
        if (isset($_POST["FuelTypeID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleFuelType();
            if (empty($RET)) {
                $vehicle_fuel_type = $this->_registry->vehicle->getLastOfType('tbl_fuel_type', 'Fuel_Type_ID');
                die(json_encode(['OK', $vehicle_fuel_type]));
            } else {
                die(json_encode(['error', $vehicle_fuel_type]));
            }
        }
    }

    public function addVehicleMakeNameAjax() {
        if (isset($_POST["MakeName"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleMakeName();
            if (empty($RET)) {
                $vehicle_type = $this->_registry->vehicle->getLastOfType('tbl_vehicle_type', 'Vehicle_Type_ID');

                die(json_encode(['OK', $vehicle_type]));
            } else {
                die(json_encode(['error', $vehicle_type]));
            }
        }
    }

    public function addVehicleModelAjax() {
        if (isset($_POST["ModelID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleModel();
            if (empty($RET)) {
                $vehicle_model = $this->_registry->vehicle->getLastOfType('tbl_vehicle_model', 'Model_ID');

                die(json_encode(['OK', $vehicle_model]));
            } else {
                die(json_encode(['error', $vehicle_model]));
            }
        }
    }

    public function addVehicleUsageType() {
        if (isset($_POST["UsageTypeID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleUsageType();
            if (empty($RET)) {
                $vehicleUsageType = $this->_registry->vehicle->getLastOfType('tbl_vehicle_usage_type', 'Usage_Type_ID');

                die(json_encode(['OK', $vehicleUsageType]));
            } else {
                die(json_encode(['error', $vehicleUsageType]));
            }
        }
    }

    public function addVehicleZone() {
        if (isset($_POST["ZoneID"])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $RET = $this->_registry->vehicle->setData($_POST)->addVehicleZone();
            if (empty($RET)) {
                $vehicleZone = $this->_registry->vehicle->getLastOfType('tbl_garage_vehicle_zone', 'Zone_ID');
                die(json_encode(['OK', $vehicleZone]));
            } else {
                die(json_encode(['error', $vehicleZone]));
            }
        }
    }

    public function WeighBrigeListRequest() {
        $cond = '';
        if (isset($_GET['WeighBridge_Date']) && isset($_GET['CheckedValue'])) {
            $Check = $_GET['CheckedValue'];
            if ($Check == 1) {
                $cond = 'WeighBridge_Date = "' . smc_escape($_GET['WeighBridge_Date']) . '"';
            } else if ($Check == 2) {
                $Year = smc_escape($_GET['WeighBridge_Date'][0]);
                $Month = smc_escape($_GET['WeighBridge_Date'][1]);
                $cond = 'MONTH(WeighBridge_Date) = "' . $Month . '" AND YEAR(WeighBridge_Date) = "' . $Year . '"';
            } else if ($Check == 3) {
                $Year = smc_escape($_GET['WeighBridge_Date'][0]);
                $cond = 'YEAR(WeighBridge_Date) = "' . $Year . '"';
            }
        }
        if (isset($_GET['WeighBridge_Date_From']) && isset($_GET['WeighBridge_Date_To']) && isset($_GET['CheckedValue'])) {
            $Check = $_GET['CheckedValue'];
            $FromDate = $_GET['WeighBridge_Date_From'];
            $ToDate = $_GET['WeighBridge_Date_To'];
            if ($Check == 4) {
                $cond = 'WeighBridge_Date >= "' . $FromDate . '" AND WeighBridge_Date <= "' . $ToDate . '"';
            }
        }

        $columns = array(
            array('db' => 'Vehicle_Registration_Number', 'dt' => 0),
            array('db' => 'Amount', 'dt' => 1),
            array('db' => 'Is_Paid', 'dt' => 2,
                  "formatter" => function($d, $row) {
                      $Statuses = [$this->_registry->expenses->getStatusName(6) . "#label-info", $this->_registry->expenses->getStatusName(12) . "#label-warning"];
                      return "<span class='label " . explode("#", $Statuses[$d - 1])[1] . "' data-currency='{$row[4]}' data-code='{$row[5]}' data-amount='{$row[6]}'>" . explode("#", $Statuses[$d - 1])[0] . "</span>";
                  }),
            array('db' => 'Is_Paid', 'dt' => 3,
                  "formatter" => function($d, $row) {
                      $Statuses = [$this->_registry->expenses->getStatusName(6) . "#label-info", $this->_registry->expenses->getStatusName(12) . "#label-warning"];

                      $html = "<div class='btn-group' >";
                      $html .= "<button type='button' " . ($d == 1 ? 'disabled ' : '') . " class='btn btn-default  dropdown-toggle' data-toggle='dropdown' aria-expanded='false'  >";
                      $html .= "<i class='fa fa-pencil'> <span class='caret'></span></i>";
                      $html .= "</button><ul class='dropdown-menu Paid_Status' data-id='{$row[7]}' role='menu' style='cursor:pointer' name='Is_Paid' >";
                      for ($x = 0; $x < count($Statuses); $x++) {
                          if ($d - 1 != $x)
                              $html .= "<li value='" . ($x + 1) . "'><a href='#'>" . explode("#", $Statuses[$x])[0] . "</a></li>";
                      }
                      $html .= "</ul></div>";
                      return $html;
                  }),
            array('db' => 'Currency_ID', 'dt' => 4),
            array('db' => 'Weighbridge_Vehicle_ID', 'dt' => 5),
            array('db' => 'Weighbridge_Amount', 'dt' => 6),
            array('db' => 'Weighbridge_ID', 'dt' => 7)
        );

        $key = 'Weighbridge_Vehicle_ID';
        $table = 'vehicle_weighbridge_list';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function WeighbridgeListAjax() {
        if (isset($_GET["Is_Paid"]) && isset($_GET["Weighbridge_ID"])) { // to update Status
            $logged_id = Session::getUserID();
            array_push($_GET, $logged_id);
            $StatusUpdate = $this->_registry->expenses->setData($_GET)->submitPaidWeighBridge(intval($_GET["Is_Paid"]), intval($_GET["Weighbridge_ID"]));
            die(empty($StatusUpdate) ? "OK" : "error");
        }
    }

    public function CheckinCheckoutAjax() {
        if (isset($_GET['VID'])) {
            $id = $_GET['VID'];
            $dailyCheckup = $this->_registry->vehicle->checkInOut($id);
            die(json_encode($dailyCheckup));
        }
    }

    //    public function FuelListAjax() {
    //        if (isset($_GET['Date'])) {
    //
    //            $year = $_GET['Date'][0];
    //            $month = $_GET['Date'][1];
    //
    //            $fuelList = $this->_registry->vehicle->viewFuelConsumbtionPerMonth($month, $year);
    //            die(json_encode($fuelList));
    //        }
    //    }

    public function addVehicleCheckupRequest() {
        $logged_id = Session::getUserID();
        array_push($_POST, $logged_id);
        $submit = $this->_registry->vehicle->setData($_POST)->addVehicleCheckup();
        die(json_encode(empty($submit) ? ["ok", ""] : ["error", $submit[0]]));
    }

    public function vehiclecheckupListRequest() {

        $cond = '';

        if (isset($_GET['vehicle_checkup_id'])) {
            $vehicle_checkup_id = $_GET['vehicle_checkup_id'];
            $RET = $this->_registry->vehicle->deleteVehicleCheckup($vehicle_checkup_id);
            die(json_encode(empty($RET) ? ["ok", ""] : ["error", $RET[0]]));
        }
        $columns = array(
            array('db' => 'Vehicle_Code','formatter' => function($d, $row) {
                return $d . '-' . $row['Vehicle_Registration_Number'] . '-' . $row['Vehicle_Type_Name'];
            }),'Vehicle_Name', 'Employee_Name',
            'checkup_date', 
            array('db' => 'vehicle_milage', 'formatter' => function($d, $row) {
                return $d . ' (' . CommonLanguage::getMessage('km') . ' )';
            }),
            array('db' => 'vehicle_action', 'formatter' => function($d) {
                $Statuses = [$this->_registry->expenses->getStatusName(35) . "#label-complete",
                             $this->_registry->expenses->getStatusName(34) . "#label-success",
                             $this->_registry->expenses->getStatusName(16) . "#label-info"];
                return '<span class="label ' . explode("#", $Statuses[$d])[1] . '" data-status="' . $d . '">' . explode("#", $Statuses[$d])[0] . '</span>';
            }),
            'checkup_note',
            array('db' => 'vehicle_checkup_id', 'formatter' => function($d, $row) {
                $html = Forms::action_snippet(["color" => "success-darker", "isDropDown" => true, "data_id" => $d,
                                               "ActionOption" => [
                                                   ["title" => CommonLanguage::getMessage("Edit"),
                                                    "class" => "Edit",
                                                    "icon" => "fa-pencil",
                                                    "permission" => "edit_vehicle_checkup"
                                                   ],
                                                   ["title" => CommonLanguage::getMessage("delete"),
                                                    "class" => "Delete",
                                                    "icon" => "fa-trash",
                                                    "permission" => "delete_vehicle_checkup"
                                                   ]
                                               ]]);
                return $html;
            }), 'Vehicle_Registration_Number','Vehicle_Type_Name'
        );
        $key = 'vehicle_checkup_id';
        $table = '(select tbl_vehicle_checkup.*,view_employees.Employee_Name,tbl_vehicle_type.*,tbl_garage_vehicle.Vehicle_Code, tbl_garage_vehicle.Vehicle_Registration_Number,tbl_garage_vehicle.Vehicle_Name
                from tbl_vehicle_checkup
                join tbl_garage_vehicle on (tbl_vehicle_checkup.vehicle_id = tbl_garage_vehicle.Vehicle_ID)
                join `tbl_vehicle_type` on (tbl_vehicle_type.Vehicle_Type_ID = tbl_garage_vehicle.Vehicle_ID)
                left join view_employees on (view_employees.Employee_ID = tbl_garage_vehicle.driver_emp_id)
                ) as dummy_table';
        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }

    public function ViewVehicleCheckupByID() {
        $RET = $this->_registry->vehicle->ViewVehicleCheckupByID($_GET['vehicle_checkup_id']);
        die(json_encode($RET));
    }

    public function addVehicleMecaniqueRequest() {
        $logged_id = Session::getUserID();
        array_push($_POST, $logged_id);
        $submit = $this->_registry->vehicle->setData($_POST)->addVehicleMecanique();
        die(json_encode(empty($submit) ? ["ok", ""] : ["error", $submit[0]]));
    }

    public function vehiclemecaniqueListRequest() {

        $cond = '';

        if (isset($_GET['vehicle_mecanique_id'])) {
            $vehicle_mecanique_id = $_GET['vehicle_mecanique_id'];
            $RET = $this->_registry->vehicle->deleteVehicleMecanique($vehicle_mecanique_id);
            die(json_encode(empty($RET) ? ["ok", ""] : ["error", $RET[0]]));
        }
        $columns = array(
            array('db' => 'Vehicle_Code', 'formatter' => function($d, $row) {
                return $d . '-' . $row['Vehicle_Registration_Number'] . '-' . $row['Vehicle_Type_Name'];
            }),'Vehicle_Name',
            'Employee_Name',
            'mecanique_date',
            'mecanique_year',
            'mecanique_note',
            array('db' =>'vehicle_mecanique_id',  'formatter' => function($d, $row) {
                $html = Forms::action_snippet(["color" => "success-darker", "isDropDown" => true, "data_id" => $d,
                                               "ActionOption" => [
                                                   ["title" => CommonLanguage::getMessage("Edit"),
                                                    "class" => "Edit",
                                                    "icon" => "fa-pencil",
                                                    "permission" => $_GET['is_syndicate'] ? "edit_vehicle_syndicate" :  "edit_vehicle_mecanique"
                                                   ],
                                                   ["title" => CommonLanguage::getMessage("delete"),
                                                    "class" => "Delete",
                                                    "icon" => "fa-trash",
                                                    "permission" => $_GET['is_syndicate'] ? "delete_vehicle_syndicate" : "delete_vehicle_mecanique"
                                                   ]
                                               ]]);
                return $html;
            }), 'Vehicle_Registration_Number','Vehicle_Type_Name'
        );
        $key = 'vehicle_mecanique_id';
        $table = '(select tbl_vehicle_mecanique.*,view_employees.Employee_Name,tbl_vehicle_type.*,tbl_garage_vehicle.Vehicle_Code,tbl_garage_vehicle.Vehicle_Registration_Number,tbl_garage_vehicle.Vehicle_Name from
                tbl_vehicle_mecanique join tbl_garage_vehicle on (tbl_vehicle_mecanique.vehicle_id = tbl_garage_vehicle.Vehicle_ID)
                left join `tbl_vehicle_type` on (tbl_vehicle_type.Vehicle_Type_ID = tbl_garage_vehicle.Vehicle_ID)
                left join view_employees on (view_employees.Employee_ID = tbl_garage_vehicle.driver_emp_id)
                ) as dummy_table';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' is_syndicate= "'.$_GET['is_syndicate'].'" ');

        echo json_encode($data);
    }

    public function ViewVehicleMecaniqueByID() {
        $RET = $this->_registry->vehicle->ViewVehicleMecaniqueByID($_GET['vehicle_mecanique_id']);
        die(json_encode($RET));
    } 
    public function getMaxVehicleCode() {
        $RET = $this->_registry->vehicle->getMaxVehicleCode();
        die(json_encode($RET));
    }

    public function vehiclemaintenanceListRequest() {
        $cond = '';
        if(!empty($_GET['main_filter'])){
            if($_GET['main_filter'] == 1){
                $cond.= ' and (
                (insurance_date > now() and insurance_date is not null) 
                or (concat_ws("-",last_mecanique_year,mecanique_month,"01") > now()  and last_mecanique_year is not null)
                or ( last_check - last_oil_change > Vehicle_Oil_Change  and last_oil_change is not null)
                or ( last_check - last_maintainence > Vehicle_Maintenance_Period  and last_maintainence is not null)
                )';
            }else{
                $cond.= ' and (
                (insurance_date < now() and insurance_date is not null) 
                or (concat_ws("-",last_mecanique_year,mecanique_month,"01") < now() and last_mecanique_year is not null)
                or ( last_check - last_oil_change < Vehicle_Oil_Change  and last_oil_change is not null)
                or ( last_check - last_maintainence < Vehicle_Maintenance_Period  and last_maintainence is not null)
                )';
            }
        }
        $columns = array(
            array('db' => 'Vehicle_Code','formatter' => function($d, $row) {
                return $d . '-' . $row['Vehicle_Registration_Number'] . '-' . $row['Vehicle_Type_Name'];
            }),'Vehicle_Name',
            array('db' => 'last_check', 'formatter' => function($d, $row) {
                return $d . ' ( ' . CommonLanguage::getMessage('km') . ' )';
            }),
            array('db' => 'last_oil_change', 'formatter' => function($d, $row) {
                return empty($d) ? '--- ---' : ($row['last_check'] - $d >= $row['Vehicle_Oil_Change'] ? '<div><span><i class="fa fa-minus-circle fa-2x" style="color:red"></i></span></div>' : '<div><span><i class="fa fa-check-circle fa-2x"style="color:green"></i></span></div>');
            }),
            array('db' => 'last_maintainence', 'formatter' => function($d, $row) {
                return empty($d) ? '--- ---' : ($row['last_check'] - $d >= $row['Vehicle_Maintenance_Period'] ? '<div><span><i class="fa fa-minus-circle fa-2x" style="color:red"></i></span></div>' : '<div><span><i class="fa fa-check-circle fa-2x" style="color:green"></i></span></div>');
            }),
            array('db' => 'last_mecanique_year', 'formatter' => function($d, $row) {
                $valid_year = intval(date('Y'));
                if (intval(date('m')) < intval($row['mecanique_month']))
                    $valid_year--;
                return empty($d) ? '--- ---' : ($d <= $valid_year ? '<div><span><i class="fa fa-minus-circle fa-2x" style="color:red"></i></span></div>' : '<div><span><i class="fa fa-check-circle fa-2x" style="color:green"></i></span></div>');
            }),
            array('db' => 'insurance_date', 'formatter' => function($d, $row) {
                $today = date('Y-m-d');
                return empty($d) ? '--- ---' : ($d < $today ? '<div><span><i class="fa fa-minus-circle fa-2x" style="color:red"></i></span></div>' : '<div><span><i class="fa fa-check-circle fa-2x" style="color:green"></i></span></div>');
            }),'Vehicle_Registration_Number', 'Vehicle_Oil_Change', 
            'Vehicle_Maintenance_Period', 'mecanique_month',  'Vehicle_Type_Name','insurance_date'
        );
        $key = 'Vehicle_ID';
        $table = '(select tbl_garage_vehicle.*,tbl_vehicle_type.*  
                    from tbl_garage_vehicle  left join `tbl_vehicle_type`
                  on (tbl_vehicle_type.Vehicle_Type_ID = tbl_garage_vehicle.Vehicle_ID) ) as dummy_table';
        $data = DataTable::complex($_GET, $table, $key, $columns,'1=1 '. $cond);

        echo json_encode($data);
    }

    public function FuelListRequest() {
        $from_date = empty($_GET['from_date']) ? date('Y-m-01') : $_GET['from_date'];
        $to_date = empty($_GET['to_date']) ? Date::getToday() : $_GET['to_date'];
        $cond = '';
        $columns = array(
            array('db' => 'Vehicle_Registration_Number', 'dt' => 0, 'formatter' => function($d, $row) {
                return $d . " - " . $row[5] . " - " . $row[6];
            }),
            array('db' => 'Vehicle_Fuel_Consumption', 'dt' => 1, 'formatter' => function($d, $row) {
                return $d . ' (' . CommonLanguage::getMessage('L') . ')';
            }),
            array('db' => 'max_milage', 'dt' => 2, 'formatter' => function($d, $row) {

                return $d - $row[4] . ' (' . CommonLanguage::getMessage('km') . ')';
            }),
            array('db' => 'Vehicle_Fuel_Consumption', 'dt' => 3, 'formatter' => function($d, $row) {

                return (((($row[2] - $row[4]) / 100) * $d) . ' (' . CommonLanguage::getMessage('L') . ')');
            }),
            array('db' => 'min_milage', 'dt' => 4),
            array('db' => 'Vehicle_Code', 'dt' => 5),
            array('db' => 'Vehicle_Type_Name', 'dt' => 6),
        );
        $key = 'Vehicle_ID';
        $table = '
(SELECT 
tbl_vehicle_checkup.checkup_date,tbl_garage_vehicle.Vehicle_ID,tbl_vehicle_type.*,
tbl_garage_vehicle.Vehicle_Fuel_Consumption,tbl_garage_vehicle.Vehicle_Registration_Number,
tbl_garage_vehicle.Vehicle_Code,min(tbl_vehicle_checkup.`vehicle_milage`) as min_milage,max(tbl_vehicle_checkup.vehicle_milage) as max_milage 
FROM  tbl_garage_vehicle join `tbl_vehicle_checkup` on (tbl_garage_vehicle.Vehicle_ID = tbl_vehicle_checkup.vehicle_id) 
   join `tbl_vehicle_type` on (tbl_vehicle_type.Vehicle_Type_ID = tbl_garage_vehicle.Vehicle_ID)
WHERE tbl_vehicle_checkup.`vehicle_action`  = 0  and  `checkup_date` BETWEEN "' . $from_date . '" and "' . $to_date . '"  group by tbl_vehicle_checkup.`vehicle_id`) as dymmy ';

        $data = DataTable::complex($_GET, $table, $key, $columns, $cond);

        echo json_encode($data);
    }
    public function submitRentType(){
        $submit = $this->_registry->vehicle->setData($_POST)->submitRentType();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success' ] : [$submit[0], 'danger']));
    }
    public function getRentTypeData(){
        $data = CommonFunctions::CommonView('rent_type_list',['rent_type_id'],[$_GET['rent_type_id']]);
        die(json_encode($data));

    }
    public function deleteRentType(){
        $delete_rent_type = $this->_registry->vehicle->setData($_GET)->deleteRentType();
        die(empty($delete_rent_type) ? "ok" : "error");
    }
    public function vehicle_rents_ajax() {

        $columns = array('Vehicle_Name','Employee_Name','rent_type_name','rent_date',
                         array('db' => 'rent_amount', 'dt' => 4,"formatter"=>function($d,$row){
                             return $d.' '.$row[6];
                         }),  array('db' => 'rent_id', 'dt' => 5, 'formatter' => function($d, $row) {
                             $html = Forms::action_snippet(["color" => "success-darker", "isDropDown" => false, "data_id" => $d,
                                                            "ActionOption" => [
                                                                ["title" => CommonLanguage::getMessage("Edit"),
                                                                 "class" => "Edit",
                                                                 "icon" => "fa-pencil",
                                                                 "permission" => "edit_vehicle_rents"
                                                                ],
                                                                //                                                   ["title" => CommonLanguage::getMessage("delete"),
                                                                //                                                    "class" => "Delete",
                                                                //                                                    "icon" => "fa-trash",
                                                                //                                                    "permission" => "delete_vehicle_mecanique"
                                                                //                                                   ]
                                                            ]]);
                             return $html;
                         }),'Currency_Symbol'

                        );
        $key = 'rent_id';
        $table = 'vehicle_rents';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function get_vehicle_rent_amount(){
        $data = $this->_registry->vehicle->get_vehicle_rent_amount($_GET['id']);
        die(json_encode($data));
    } 
    public function getVehicleInfo(){
        $data = $this->_registry->vehicle->getVehicleInfo($_GET['current_vehicle_id']);
        die(json_encode($data));
    }
    public function get_vehicle_rent_by_id(){
        $data = $this->_registry->vehicle->get_vehicle_rent_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function add_vehicle_rent(){
        $insert = $this->_registry->vehicle->setData($_POST)->add_vehicle_rent();
        die(json_encode(empty($insert) ? 'OK' : 'error'));
    }
    public function edit_vehicle_rent(){
        $edit = $this->_registry->vehicle->setData($_POST)->edit_vehicle_rent();
        die(json_encode(empty($edit) ? 'OK' : 'error'));
    }

    public function get_multi_rent_payment_ajax(){
        $data = $this->_registry->vehicle->get_multi_rent_payment($_GET['date'],$_GET['rent_type']);
        $html=Forms::build_table_html($data);
        die($html);
    }

    public function add_multi_rent_pay(){
        $insert = $this->_registry->vehicle->setData($_POST)->add_multi_rent_pay();
        die(empty($insert) ? 'OK' : 'error');
    }

    public function deleteVehicleExpense() {
        $delete = $this->_registry->vehicle->setData($_GET)->deleteVehicleExpense();
        die(empty($delete) ? "ok" : $delete[0]);
    }

    public function enable_disable_vehicle(){
        $data = $this->_registry->vehicle->setData($_POST)->enable_disable_vehicle();
        die(empty($data) ? 'ok' : 'error');
    }


}
