<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use App\Models\Station;
use App\Models\Requests;

class StationController extends Controller
{
    public function headerView($id = ''){
        $headerDetails = null;
        if (Auth::user()) {        
            return view('dashboard');
        } else {
            return Redirect::to('/');
        }
    }

    public function list(){
        return view('station.list');
    }
    public function getList(Request $request){
        extract($request->input());
        $columns = array(0 => 'id', 1 => 'name', 2 => 'company', 3 => 'address', 4 => 'latitude', 5 => 'longitude', 6 => 'lastupdated');
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        $search = $request->input('search.value');
        $Records = DB::table('station')
                ->select('*')
                ->where(function ($query) use ($search) {
                    $query->where(DB::raw('LOWER(name)'), 'LIKE', '%' . strtolower($search) . '%');
                    $query->orwhere(DB::raw('LOWER(company)'), 'LIKE', '%' . strtolower($search) . '%');
                });

        $totalFiltered = $Records->count();
        $totalRecords = $Records->offset($start)->limit($limit)->orderBy($order, $dir)->get();
        $data = array();
        if (!empty($totalRecords)) {

            foreach ($totalRecords as $key => $record) {
                $nestedData['id'] = $record->id;
                $nestedData['lastupdated'] = $record->lastupdated;
                $nestedData['name'] = $record->name;
                $nestedData['address'] = $record->address;
                $nestedData['latitude'] = $record->latitude;
                $nestedData['longitude'] = $record->longitude;
                $nestedData['company'] = $record->company;
                $nestedData['action'] = "<a href='javascript::void(0)' data-id='$record->id' data-details='" . json_encode($record) . "' class=' show-details view-details' title='View Details'><img src='/images/view-details.png'></a>";
                
                $data[] = $nestedData;
            }
        }
        $json_data = array("draw" => intval($request->input('draw')), "recordsTotal" => intval($totalFiltered), "recordsFiltered" => intval($totalFiltered), "data" => $data,);
        echo json_encode($json_data);
    }
    public function add(Request $request){
        if ($request->is('admin/station/update*')) {
            $action = 'update';
        } else {
            $action = 'add';
        }
        return view('station.add', compact('action'));
    }
    public function addlist(Request $request){
        extract($request->input());
        $columns = array(0 => 'deleteRequests', 1 => 'name', 2 => 'address', 3=> 'latitude', 4 => 'longitude', 5 => 'company');
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        $search = $request->input('search.value');
        $Records = DB::table('requests')
                ->select('*')
                ->where(function ($query) use ($search) {
                    $query->where(DB::raw('LOWER(name)'), 'LIKE', '%' . strtolower($search) . '%');
                    $query->orwhere(DB::raw('LOWER(company)'), 'LIKE', '%' . strtolower($search) . '%');
                });
        if(!empty($action) && $action == 'add'){
            $Records = $Records->where('station_id', 0);
        }
        if(!empty($action) && $action == 'update'){
            $Records = $Records->where('station_id', '!=', 0);
        }
        $totalFiltered = $Records->count();
        $totalRecords = $Records->offset($start)->limit($limit)->orderBy($order, $dir)->get();
        $data = array();
        if (!empty($totalRecords)) {

            foreach ($totalRecords as $key => $record) {
                $nestedData['deleteRequests'] = "<input type='checkbox' value=".$record->id." name='requestId' class='checkbox text-center' style='zoom:1.7'/>";
                $nestedData['name'] = $record->name;
                $nestedData['address'] = $record->address;
                $nestedData['latitude'] = $record->latitude;
                $nestedData['longitude'] = $record->longitude;
                $nestedData['company'] = $record->company;
                $nestedData['action'] = "<a href='javascript::void(0)' data-id='$record->id' data-details='" . json_encode($record) . "' class=' show-details view-details' title='View Details'><img src='/images/view-details.png'></a>";
                $data[] = $nestedData;
            }
        }
        $json_data = array("draw" => intval($request->input('draw')), "recordsTotal" => intval($totalFiltered), "recordsFiltered" => intval($totalFiltered), "data" => $data,);
        echo json_encode($json_data);
    }
    public function save(Request $request){
        try {
            extract($request->All());

            $commonInfo = array(
                "Kundetoaletter" => !empty($Kundetoaletter),
                "Handikaptoalett" => !empty($Handikaptoalett),
                "Bilvask (maskin)" => !empty($Bilvask_Maskin),
                "Bilvask (selvvask)" => !empty($Bilvask_Selvvask),
                "Gass" => !empty($Gass),
                "Tilhengerleie" => !empty($Tilhengerleie),
                "Landestasjoner" => !empty($Landestasjoner),
                "Telefonnummer" => "",
                "Beskrivelse" => "",
                "Døgnåpent" => !empty($dognapent) ? false : true,
            );
            if (!empty($dognapent)) {
                $info = array_merge($commonInfo, array(
                    "Hours" => array(
                        'Mandag' => "$startMonday-$endMonday",
                        'Tirsdag' => "$startTuesday-$endTuesday",
                        'Onsdag' => "$startWednesday-$endWednesday",
                        'Torsdag' => "$startThursday-$endThursday",
                        'Fredag' => "$startFriday-$endFriday",
                        'Lørdag' => "$startSaturday-$endSaturday",
                        'Søndag' => "$startSunday-$endSunday",
                    )
                ));
            } else {
                $info = array_merge($commonInfo, array(
                   "Hours" => (object)[]
                ));
            }

            $infoJson = json_encode($info, JSON_UNESCAPED_UNICODE);
            if(!empty($station_id)){
                $addRecord = Station::find($station_id);
                Requests::where('station_id', $station_id)->delete();
            }else{
                $addRecord = new Station();
                $addRecord->logoid = 0;
                Requests::where('id', $request_id)->delete();
            }
            $addRecord->name = $name;
            $addRecord->company = $company;
            $addRecord->latitude = $latitude;
            $addRecord->longitude = $longitude;
            $addRecord->address = $address;
            $addRecord->info = $infoJson;
            $addRecord->save();
            return response()->json([
                'message' => !empty($station_id) ? "Station update successfully" : "Station added successfully"
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'message' => "Something went wrong please try again later",
            ], 400);
        }
    }
    public function delete(Request $request){
        try {
            extract($request->Input());
            $requestIds = explode(',',$requestIds);
            Requests::whereIn('id', $requestIds)->delete();
            return response()->json([
                'message' => "Station request deleted successfully",
                'requestIds'=>$requestIds
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'message' => "Something went wrong please try again later",
            ], 400);
        }
    }
}
