<?php

if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjActionUserSearch extends pjAdmin
{
   
    
    public function pjActionUserSearchIndex()
        {
            $this->checkLogin();
            if (!pjAuth::factory()->hasAccess())
            {
                $this->sendForbidden();
                return;
            }
            $this->appendCss('datepicker3.css', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
            $this->appendJs('bootstrap-datepicker.js', PJ_THIRD_PARTY_PATH . 'bootstrap_datepicker/');
            $this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
            $this->appendJs('pjAdminUserSearch.js');
        }
    
    public function pjActionGetSearch()
        { 
            $this->checkLogin();
            $this->setAjax(true);
            
            if ($this->isXHR())
            {
                // $pjBookingModel = pjUserSearchHistoryModel::factory() 
                //  ->select("t1.*, t2.content as fleet")
                // ->join('pjMultiLang', "t2.model='pjFleet' AND t2.foreign_id=t1.fleet_id AND t2.field='fleet' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
                // ->findAll()
                // ->getData();
                $pjBookingModel = pjUserSearchHistoryModel::factory() 
                ->select("t1.*, t2.content as fleet")
                ->join('pjMultiLang', "t2.model='pjFleet' AND t2.foreign_id=t1.fleet_id AND t2.field='fleet' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
                ->orderBy("t1.booking_date DESC")
                ->findAll()
                ->getData();

                // $column = 'date_time';
                $column = 'booking_date';
                $direction = 'DESC';
                if ($this->_get->check('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC')))
                {
                    $column = $this->_get->toString('column');
                    // if($column == 'date_time'){
                    //     $column = 'booking_date';
                    // }
                    $direction = strtoupper($this->_get->toString('direction'));
                }
                
                $total = count($pjBookingModel);
             
                $rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
                $pages = ceil($total / $rowCount);
                $page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
                $offset = ((int) $page - 1) * $rowCount;
                if ($page > $pages)
                {
                    $page = $pages;
                }
                
                $data = array();
                
                $data = $pjBookingModel;
               
             foreach ($data as $k => $v) {
    
                // Format booking_date
                if (!empty($v['booking_date'])) {
                    $v['booking_date'] = date(
                        $this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'],
                        strtotime($v['booking_date'])
                    );
                }
            
                // Format return_date
                if (!empty($v['return_date'])) {
                    $v['return_date'] = date(
                        $this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'],
                        strtotime($v['return_date'])
                    );
                }
            
                // Format distance fields
                $v['distance'] = isset($v['distance']) ? (int)$v['distance'] . ' km' : '0 km';
                $v['extra_stop_distance'] = isset($v['extra_stop_distance']) ? (int)$v['extra_stop_distance'] . ' km' : '0 km';
            
                if (!empty($v['extra_stop_address'])) {
                    if (is_string($v['extra_stop_address'])) {
                        $decoded = json_decode($v['extra_stop_address'], true);
                        if (json_last_error() === JSON_ERROR_NONE) {
                            $v['extra_stop_address'] = implode(', ', $decoded);
                        }
                    } elseif (is_array($v['extra_stop_address'])) {
                        $v['extra_stop_address'] = implode(', ', $v['extra_stop_address']);
                    }
                }
                
          
                
                // Normalize all other fields (null safety or defaulting if needed)
                $v['fleet_id'] = isset($v['fleet']) ? $v['fleet'] : null;
                $v['price_id'] = isset($v['price_id']) ? pjCurrency::formatPrice($v['price_id']) : null;
                $v['from_city'] = isset($v['from_city']) ? $v['from_city'] : null;
                $v['to_city'] = isset($v['to_city']) ? $v['to_city'] : null;
                $v['extra_city'] = isset($v['extra_city']) ? $v['extra_city'] : null;
                $v['from_city_postalcode'] = isset($v['from_city_postalcode']) ? $v['from_city_postalcode'] : null;
                $v['extra_stop_postalcode'] = isset($v['extra_stop_postalcode']) ? $v['extra_stop_postalcode'] : null;
                $v['to_city_postalcode'] = isset($v['to_city_postalcode']) ? $v['to_city_postalcode'] : null;
                $v['pickup_address'] = isset($v['pickup_address']) ? $v['pickup_address'] : null;
                $v['return_address'] = isset($v['return_address']) ? $v['return_address'] : null;
                $v['booking_time'] = isset($v['booking_time']) ? $v['booking_time'] : null;
                $v['extra_stop'] = isset($v['extra_stop']) ? $v['extra_stop'] : 0;
                $v['return_status'] = isset($v['return_status']) ? $v['return_status'] : 0;
                $v['return_time'] = isset($v['return_time']) ? $v['return_time'] : null;
                $v['passengers'] = isset($v['passengers']) ? $v['passengers'] : 0;
                $v['luggage'] = isset($v['luggage']) ? $v['luggage'] : 0;
                $v['luggage_trolleys'] = isset($v['luggage_trolleys']) ? $v['luggage_trolleys'] : 0;
                $v['luggage_koffers'] = isset($v['luggage_koffers']) ? $v['luggage_koffers'] : 0;
            
                // Final assignment back to $data
                $data[$k] = $v;
            }
            
                // foreach($data as $k => $v)
                // { 
                //     $v['booking_date']  = date($this->option_arr['o_date_format'] . ', ' . $this->option_arr['o_time_format'] , strtotime($v['booking_date']));
                //     $v['distance'] = (int) $v['distance'] . ' km';
                //     $v['return_status'] = $v['return_status'];
                //     $v['extra_stop'] = $v['extra_stop'];
                //     $data[$k] = $v;
                // }
        
                self::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
            }
            exit;
        }
    
    public function pjActionDeleteUserSearch()
        {
            $this->setAjax(true);
            
            if (!$this->isXHR())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
            }
            if (!self::isPost())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
            }
            if (!pjAuth::factory()->hasAccess())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
            }
            if (!($this->_get->toInt('id')))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
            }
            $pjBookingModel = pjUserSearchHistoryModel::factory();
            $arr = $pjBookingModel->find($this->_get->toInt('id'))->getData();
            if (!$arr)
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Fleet not found.'));
            }
            $id = $this->_get->toInt('id');
            if ($pjBookingModel->setAttributes(array('id' => $id))->erase()->getAffectedRows() == 1)
            {
                self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Fleet has been deleted'));
            }else{
                self::jsonResponse(array('status' => 'ERR', 'code' => 105, 'text' => 'Fleet has not been deleted.'));
            }
            exit;
        }
    
    public function pjActionDeleteUserSearchBulk()
        {
            $this->setAjax(true);
            if (!$this->isXHR())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
            }
            if (!self::isPost())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP method not allowed.'));
            }
            if (!pjAuth::factory()->hasAccess())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Access denied.'));
            }
            if (!$this->_post->has('record'))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 103, 'text' => 'Missing, empty or invalid parameters.'));
            }
            $record = $this->_post->toArray('record');
            if (empty($record))
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 104, 'text' => 'Missing, empty or invalid parameters.'));
            }
            $pjBookingModel = pjUserSearchHistoryModel::factory();
            $pjBookingModel->reset()->whereIn('id', $record)->eraseAll();
           
            self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Fleet(s) has been deleted.'));
            exit;
        }
    
}
?>