<?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 Testonroad
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Testonroad extends Base_Controller {

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

    public function viewonroad($cardid = null) {
       $this->load->template = 'mainviewtestride';
        $this->load->model(array('card_model', 'onroad_model', 'vehicle_model'));
        $vehicle = $this->vehicle_model->get(array('testtype' => 2));
        $card = $this->card_model->detail(array('id' => $cardid));
        $onroad = $this->onroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => 'onroad.ordernumber ASC, onroad.vehicleid ASC'));
        $result = array();
        $current = array();
        foreach($onroad 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){
			if(isset($r['stack'])){
             $maxcount = (count($r['stack']) > $maxcount) ? count($r['stack']) : $maxcount;
			}
        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('testonroad/_viewonroad', array('data' => $result, 'card' => $card, 'current' => $current));
        } else {
            $this->load->view('testonroad/viewonroad', array('data' => $onroad, 'card' => $card, 'current' => $current));
        }
        // if ($this->input->is_ajax_request()) {
        //     echo $this->load->partials('testonroad/_viewonroad', array('data' => $result, 'card' => $card, 'current' => $current));
        // } else {
        //     $this->load->view('testonroad/viewonroad', array('data' => $result, 'card' => $card, 'current' => $current));
        // }
    }
}

    public function onroad($cardid = null) {
        // check login access
        if (!$this->is_login) {
            redirect(parent::BACKOFFICE_LOGIN);
        }
        $this->load->model(array('card_model', 'vehicle_model', 'register_model', 'onroad_model'));
        $this->load->helper('form');
        $vehicle = $this->vehicle_model->get(array('testtype' => 2, 'status' => 1, 'orderby' => 'vehicle.id ASC'));
        $register = $this->register_model->get(array('cardid' => $cardid, 'orderby' => 'register.id ASC'));
        $orderedonroad = array();
        $count = count($vehicle);
        for ($i = 0; $i < $count; $i++) {
            if (!in_array($vehicle[$i]['id'], array_column($orderedonroad, 'id'))) {
                $maxorder = $this->onroad_model->getmaxorder(array('vehicleid' => $vehicle[$i]['id'], 'cardid' => $cardid));
                $orderedonroad[] = array(
                    'vehicleid' => $vehicle[$i]['id'],
                    'maxorder' => ($maxorder['maxvehicleorder']) ? $maxorder['maxvehicleorder'] : 0
                );
            }
        }
        $vehiclecount = count($orderedonroad);
        $insert = array();
        for ($j = 0; $j < $vehiclecount; $j++) {
            if (isset($register[0])) {
                $pointer = $register[0];
                $check = $this->onroad_model->check(array(
                    'registerid' => $pointer['id']
                ));
                if ($check == 0) {
                    $neworder = $orderedonroad[$j]['maxorder'] + 1;
                    $insert[] = array(
                        'registerid' => $pointer['id'],
                        'vehicleid' => $orderedonroad[$j]['vehicleid'],
                        'status' => 1,
                        'ordernumber' => $neworder
                    );
                    $orderedonroad[$j]['maxorder'] = $neworder;
                }
                unset($register[0]);
                $register = array_values($register);
            }
            if ($register && $j == $vehiclecount - 1) {
                $j = -1;
            }
        }
        if ($insert) {
            $this->onroad_model->insert($insert, false, true);
        }
        $onroad = $this->onroad_model->get(array('status' => 1, 'cardid' => $cardid, 'orderby' => '`onroad`.`vehicleid` ASC, `onroad`.`ordernumber` ASC'));
        $return = array();
        foreach ($vehicle as $res2) {
            $return[$res2['name']] = array();
        }
        foreach ($onroad 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->onroad_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('testonroad/onroad', 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', 'onroad_model'));
        $detail = $this->onroad_model->detail(array('id' => $id));
        if (!$detail) {
            redirect('backoffice/testonroad/onroad/' . $cardid);
        }
        $onroad = $this->onroad_model->get(array('status' => 1, 'orderby' => '`onroad`.`vehicleid` ASC, `onroad`.`ordernumber` ASC'));
        $pointerstack = null;
        $orderedonroad = array();
        foreach ($onroad as $res) {
            if (!in_array($res['vehicleid'], array_column($orderedonroad, 'vehicleid'))) {
                $orderedonroad[] = array('vehicleid' => $res['vehicleid']);
            }
            $currindex = array_search($res['vehicleid'], array_column($orderedonroad, 'vehicleid'));
            if ($res['id'] === $detail['id']) {
                $pointerstack = $currindex;
            }
            if ($currindex !== false) {
                $orderedonroad[$currindex]['stack'][] = array(
                    'id' => $res['id'],
                    'registerid' => $res['registerid'],
                    'ordernumber' => $res['ordernumber']
                );
                if (!isset($orderedonroad[$currindex]['maxorder'])) {
                    $orderedonroad[$currindex]['maxorder'] = $res['ordernumber'];
                } else {
                    if ($orderedonroad[$currindex]['maxorder'] < $res['ordernumber']) {
                        $orderedonroad[$currindex]['maxorder'] = $res['ordernumber'];
                    }
                }
            }
        }
        $removestack = array_search($detail['id'], array_column($orderedonroad[$pointerstack]['stack'], 'id'));
        unset($orderedonroad[$pointerstack]['stack'][$removestack]);
        $this->onroad_model->update(array('status' => 3), array('id' => $detail['id']));
        $delimiter = array_search($detail['vehicleid'], array_column($orderedonroad, 'vehicleid'));
        $slicedstack = array_slice($orderedonroad, $delimiter);
        if (!$slicedstack) {
            redirect('backoffice/testonroad/onroad/' . $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 `onroad` 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->onroad_model->update_countdown($detail['vehicleid']);
        redirect('backoffice/testonroad/onroad/' . $cardid);
    }

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

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

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

}
