<?php

/*
 * Copyright (c) 2019 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 *  contact@earworks.co.id
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Testride
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Testride extends Base_Controller {

    public $allowed_role = array(1, 2, 3);

    public function index() {
        $this->load->model('card_model');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('testtype', 'lang:testtype', 'trim|numeric|required');
        $this->form_validation->set_rules('cardid', 'lang:cardname', 'trim|numeric|required');
        if ($this->form_validation->run() === false) {

            $this->load->view('testride/index', array(
                'card' => $this->card_model->dropdown()
            ));
        } else {
            if ($this->input->post('testtype', true) == 1) {
                redirect('backoffice/testride/offroad/' . $this->input->post('cardid', true));
            } elseif ($this->input->post('testtype', true) == 2) {
                redirect('backoffice/testonroad/onroad/' . $this->input->post('cardid', true));
            } else {
                redirect('backoffice/testride');
            }
        }
    }
//    public function viewoffroad($cardid = null) {
//        $this->load->template = 'mainviewtestride';
//        $this->load->model(array('card_model', 'offroad_model'));
//        $offroad = $this->offroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => '`offroad`.`ordernumber` ASC, `offroad`.`vehicleid` ASC'));
//        $card = $this->card_model->detail(array('id' => $cardid));
//        if (!$card) {
//            redirect('backoffice/testride/offroad/' . $cardid);
//        }
//        $current = array();
//        if ($offroad) {
//            foreach($offroad as $k => $res) {
//                if(!array_key_exists($res['vehicleid'], $current)){
//                    $current[$res['vehicleid']] = $res;
//                }
//            }
//        }
//        if ($this->input->is_ajax_request()) {
//            echo $this->load->partials('testride/_viewoffroad', array('data' => $offroad, 'card' => $card, 'current' => $current));
//        } else {
//            $this->load->view('testride/viewoffroad', array('data' => $offroad, 'card' => $card, 'current' => $current));
//        }
//    }
    public function viewoffroad($cardid) {
        $this->load->template = 'mainviewtestride';
        $this->load->model(array('card_model', 'offroad_model', 'vehicle_model'));
        $vehicle = $this->vehicle_model->get(array('testtype' => 1));
        $card = $this->card_model->detail(array('id' => $cardid));
        $offroad = $this->offroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => 'offroad.ordernumber ASC, offroad.vehicleid ASC'));
        $result = array();
        $current = array();
        foreach($offroad as $k => $v) {
            $idx = array_search($v['vehicleid'], array_column($vehicle, 'id'));
            if(isset($vehicle[$idx])){
                $vehicle[$idx]['stack'][] = $v;
            }
        }
        $maxcount = 0;
        foreach($vehicle as $r){
<<<<<<< HEAD
			if(isset($r['stack'])){
             $maxcount = (count($r['stack']) > $maxcount) ? count($r['stack']) : $maxcount;
			}
=======
			if(isset($r['stack'])) {
				$maxcount = (count($r['stack']) > $maxcount) ? count($r['stack']) : $maxcount;
			}
             
>>>>>>> c97bb463d7d1b556da7e798cac7455b71d077454
        }
        for($i = 0; $i< $maxcount; $i++) {
            foreach($vehicle as $r2) {
                if(!isset($r2['stack'][$i])){
                    continue;
                }
                $result[] = $r2['stack'][$i];
            }
            if($i == 0){
                foreach($vehicle as $r3) {
                    if(!isset($r3['stack'][$i])){
                    continue;
                }
                    $current[$r3['id']] = $r3['stack'][$i];
                }
            }
        }
        if ($this->input->is_ajax_request()) {
            echo $this->load->partials('testride/_viewoffroad', array('data' => $result, 'card' => $card, 'current' => $current));
        } else {
            $this->load->view('testride/viewoffroad', array('data' => $offroad, 'card' => $card, 'current' => $current));
        }
    }

    public function offroad($cardid = null) {
        // check login access
        if (!$this->is_login) {
            redirect(parent::BACKOFFICE_LOGIN);
        }
        $this->load->model(array('card_model', 'vehicle_model', 'register_model', 'offroad_model'));
        $this->load->helper('form');
        $vehicle = $this->vehicle_model->get(array('testtype' => 1, 'status' => 1, 'orderby' => 'vehicle.id ASC'));
        $register = $this->register_model->get(array('cardid' => $cardid, 'orderby' => 'register.id ASC'));
        $orderedoffroad = array();
        $count = count($vehicle);
        for ($i = 0; $i < $count; $i++) {
            if (!in_array($vehicle[$i]['id'], array_column($orderedoffroad, 'id'))) {
                $maxorder = $this->offroad_model->getmaxorder(array('vehicleid' => $vehicle[$i]['id'], 'cardid' => $cardid));
                $orderedoffroad[] = array(
                    'vehicleid' => $vehicle[$i]['id'],
                    'maxorder' => ($maxorder['maxvehicleorder']) ? $maxorder['maxvehicleorder'] : 0
                );
            }
        }
        $vehiclecount = count($orderedoffroad);
        $insert = array();
        for ($j = 0; $j < $vehiclecount; $j++) {
            if (isset($register[0])) {
                $pointer = $register[0];
                $check = $this->offroad_model->check(array(
                    'registerid' => $pointer['id']
                ));
                if ($check == 0) {
                    $neworder = $orderedoffroad[$j]['maxorder'] + 1;
                    $insert[] = array(
                        'registerid' => $pointer['id'],
                        'vehicleid' => $orderedoffroad[$j]['vehicleid'],
                        'status' => 1,
                        'ordernumber' => $neworder
                    );
                    $orderedoffroad[$j]['maxorder'] = $neworder;
                }
                unset($register[0]);
                $register = array_values($register);
            }
            if ($register && $j == $vehiclecount - 1) {
                $j = -1;
            }
        }
        if ($insert) {
            $this->offroad_model->insert($insert, false, true);
        }
        $offroad = $this->offroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => '`offroad`.`vehicleid` ASC, `offroad`.`ordernumber` ASC'));
        $return = array();
        foreach ($vehicle as $res2) {
            $return[$res2['name']] = array();
        }
        foreach ($offroad as $res2) {
            $return[$res2['vehiclename']][] = array(
                'id' => $res2['id'],
                'registerid' => $res2['registerid'],
                'name' => $res2['name'],
                'company' => $res2['company'],
                'type' => $res2['type'],
                'vehicleid' => $res2['vehicleid']
            );
        }
        $canceldata = $this->offroad_model->get(array('cardid' => $cardid, 'status' => 3));
        if ($canceldata) {
            foreach ($canceldata as $k => $v) {
                $canceldata[$k]['name'] = $canceldata[$k]['name'] . ' - ' . $canceldata[$k]['company'];
            }
            $canceldata = array_column($canceldata, 'name', 'id');
        }
        $this->load->view('testride/offroad', array(
            'data' => $return,
            'cardid' => $cardid,
            'canceldata' => $canceldata,
            'vehicleid' => array_column($vehicle, 'name', 'id')
        ));
    }

    public function cancel($id = null, $cardid = null) {
        $this->load->model(array('vehicle_model', 'offroad_model'));
        $detail = $this->offroad_model->detail(array('id' => $id));
        if (!$detail) {
            redirect('backoffice/testride/offroad/' . $cardid);
        }
        $offroad = $this->offroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => '`offroad`.`vehicleid` ASC, `offroad`.`ordernumber` ASC'));
        $pointerstack = null;
        $orderedoffroad = array();
        foreach ($offroad as $res) {
            if (!in_array($res['vehicleid'], array_column($orderedoffroad, 'vehicleid'))) {
                $orderedoffroad[] = array('vehicleid' => $res['vehicleid']);
            }
            $currindex = array_search($res['vehicleid'], array_column($orderedoffroad, 'vehicleid'));
            if ($res['id'] === $detail['id']) {
                $pointerstack = $currindex;
            }
            if ($currindex !== false) {
                $orderedoffroad[$currindex]['stack'][] = array(
                    'id' => $res['id'],
                    'registerid' => $res['registerid'],
                    'ordernumber' => $res['ordernumber']
                );
                if (!isset($orderedoffroad[$currindex]['maxorder'])) {
                    $orderedoffroad[$currindex]['maxorder'] = $res['ordernumber'];
                } else {
                    if ($orderedoffroad[$currindex]['maxorder'] < $res['ordernumber']) {
                        $orderedoffroad[$currindex]['maxorder'] = $res['ordernumber'];
                    }
                }
            }
        }
        $removestack = array_search($detail['id'], array_column($orderedoffroad[$pointerstack]['stack'], 'id'));
        unset($orderedoffroad[$pointerstack]['stack'][$removestack]);
        $this->offroad_model->update(array('status' => 3), array('id' => $detail['id']));
        $delimiter = array_search($detail['vehicleid'], array_column($orderedoffroad, 'vehicleid'));
        $slicedstack = array_slice($orderedoffroad, $delimiter);
        if (!$slicedstack) {
            redirect('backoffice/testride/offroad/' . $cardid);
        }
        $count = count($slicedstack);
        for ($i = 0; $i < $count; $i++) {
            if (!isset($slicedstack[$i + 1])) {
                continue;
            }
            $countnext = count($slicedstack[$i + 1]['stack']);
            if (count($slicedstack[$i]['stack']) < $countnext) {

                $last = end($slicedstack[$i + 1]['stack']);
                if ($last) {
                    $neworder = $slicedstack[$i]['maxorder'] + 1;
                    $this->db->query("UPDATE `offroad` SET `vehicleid` = '{$slicedstack[$i]['vehicleid']}', `ordernumber` = '{$neworder}' WHERE `id` = '{$last['id']}'");
                    $slicedstack[$i]['stack'][] = $last;
                    unset($slicedstack[$i + 1]['stack'][$countnext - 1]);
                    $slicedstack[$i + 1]['maxorder'] = $slicedstack[$i + 1]['maxorder'] - 1;
                }
            }
        }
        $this->offroad_model->update_countdown($detail['vehicleid']);
        redirect('backoffice/testride/offroad/' . $cardid);
    }

    public function finish($id = null, $cardid = null) {
        $this->load->model('offroad_model');
        $this->offroad_model->set_finish(array('status' => 2), array('ids' => array($id)));
        redirect('backoffice/testride/offroad/' . $cardid);
    }

    public function closevehicle($id = null, $cardid = null) {
        $this->load->model(array('offroad_model', 'vehicle_model'));
        $detail = $this->vehicle_model->detail(array('id' => $id));
        if (!$detail) {
            redirect('backoffice/testride/offroad/' . $cardid);
        }
        $this->vehicle_model->update(array('status' => 2), array('id' => $detail['id']));
        $offroad = $this->offroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => '`offroad`.`vehicleid` ASC, `offroad`.`ordernumber` ASC'));
        $pointerstack = null;
        $orderedoffroad = array();
        $removedstack = array();
        foreach ($offroad as $res) {
            if ($res['vehiclestatus'] == 2) {
                $removedstack[] = $res;
                continue;
            }
            if (!in_array($res['vehicleid'], array_column($orderedoffroad, 'vehicleid'))) {
                $orderedoffroad[] = array('vehicleid' => $res['vehicleid']);
            }
            $currindex = array_search($res['vehicleid'], array_column($orderedoffroad, 'vehicleid'));
            if ($res['id'] === $detail['id']) {
                $pointerstack = $currindex;
            }
            if ($currindex !== false) {
                $orderedoffroad[$currindex]['stack'][] = array(
                    'id' => $res['id'],
                    'registerid' => $res['registerid'],
                    'ordernumber' => $res['ordernumber']
                );
                if (!isset($orderedoffroad[$currindex]['maxorder'])) {
                    $orderedoffroad[$currindex]['maxorder'] = $res['ordernumber'];
                } else {
                    if ($orderedoffroad[$currindex]['maxorder'] < $res['ordernumber']) {
                        $orderedoffroad[$currindex]['maxorder'] = $res['ordernumber'];
                    }
                }
            }
        }
        $count = count($orderedoffroad);
        if ($count == 0) {
            $ids = array_column($removedstack, 'id');
            if ($ids) {
                $this->db->query('DELETE FROM `offroad` WHERE id in(' . implode(',', $ids) . ')');
            }
        } else {
            for ($i = 0; $i < $count; $i++) {
                if (isset($removedstack[0])) {
                    $pointer = $removedstack[0];
                    $neworder = $orderedoffroad[$i]['maxorder'] + 1;
                    $orderedoffroad[$i]['stack'][] = array(
                        'id' => $pointer['id'],
                        'registerid' => $pointer['registerid'],
                        'ordernumber' => $neworder
                    );
                    $this->db->query("UPDATE `offroad` SET `vehicleid` = '{$orderedoffroad[$i]['vehicleid']}', `ordernumber` = '{$neworder}' WHERE `id` = '{$pointer['id']}'");
                    $orderedoffroad[$i]["maxorder"] = $neworder;
                    unset($removedstack[0]);
                    $removedstack = array_values($removedstack);
                }
                if ($removedstack && $i == $count - 1) {
                    $i = -1;
                }
            }
        }
        redirect('backoffice/testride/offroad/' . $cardid);
    }

    public function requeue($cardid = null) {
        $this->load->model('offroad_model');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('vehicleid', 'lang:kendaraan', 'trim|numeric|required');
        $this->form_validation->set_rules('offroadid', 'lang:visitor', 'trim|numeric|required');
        if ($this->form_validation->run() === true) {
            $input = array(
                'vehicleid' => $this->input->post('vehicleid', true),
                'offroadid' => $this->input->post('offroadid', true)
            );
            $maxorder = $this->offroad_model->getmaxorder($input);
            $this->offroad_model->update(array(
                'status' => 1,
                'vehicleid' => $input['vehicleid'],
                'ordernumber' => $maxorder['maxvehicleorder'] + 1
                    ), array('id' => $input['offroadid']));
        }
        redirect('backoffice/testride/offroad/' . $cardid);
    }

}
