<?php

namespace App\Http\Controllers;

use App\Models\UserObject;
use App\Models\ObjectModel;
use App\Models\CarReport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\CarMileageReportImport;
use App\Exports\CarReportExport;
use App\Imports\MultipleFileImport;
use App\Exports\singleExport;

use App\Models\TempFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

use App\Http\Services\ObjectService;

class ReportController extends Controller
{
    public function index(Request $request){

        $object_datas = ObjectService::getAll();

        $authUser =  Auth::user();

        // dd($authUser);

        if($request->ajax()){    
            
            $report_datas = CarReport::with('objectDetails');

            if($request->start_date && $request->end_date)
            {
               $formatted_start_date = Carbon::parse($request->start_date)->format('Y-m-d');
               $formatted_end_date = Carbon::parse($request->end_date)->format('Y-m-d');

               $report_datas = $report_datas->where('start_time','>=', $formatted_start_date. ' 00:00:00')->where('end_time','<=', $formatted_end_date. ' 23:59:59');
                    
            }

            if($request->selected_object_id){
                $filter_objects = [];
                foreach($request->selected_object_id as $obj){
                    $decoded_obj = json_decode($obj,true);
                    array_push($filter_objects,$decoded_obj['id']);
                }
                $report_datas = $report_datas->where(function ($q) use ($filter_objects) {
                        $q->whereIn('object_id',$filter_objects);
                });
            }
            else{
                if(!(Auth::user()->type === 'admin')){
                    $user_objects = UserObject::where('user_id', Auth::user()->id)->pluck('object_id');
                    if(isset($user_objects)){
                        $report_datas = $report_datas->whereIn('object_id',$user_objects);
                    }
                    else{
                        $report_datas = [];
                    }
                   
                }
            }

           

            $report_datas = $report_datas->paginate(10);

            foreach($report_datas as $report){
                $report->length = number_format((float)($report->length),2);
                // return response()->json($report,200);
            }

            return response()->json($report_datas,200);
        }
        return view('report.index',compact('object_datas','authUser'));

    }

    public function import(Request $request){
        
        try {
            
            config(['excel.import.startRow' => 8]);
            Excel::import(new MultipleFileImport, request()->file('file'));
            return response()->json(["message" => "File imported successfully"],200);

        } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
            $message = $e->getMessage();
            $errors = $e->errors();
            return back()->withError($errors,402);
        }
    }


    public function export(Request $request){
        

        $period = '';
        
        $data = ObjectModel::with('carREports');

        if(!(Auth::user()->type === 'admin')){
            $user_objects = UserObject::where('user_id', Auth::user()->id)->pluck('object_id');
            // dd($user_objects);
            if(isset($user_objects)){
                $data = $data->whereIn('id',$user_objects);
            }else{
                $data = [];
            }
           
        }
        if($request->selected_object_id){
            $filter_objects = [];
            foreach($request->selected_object_id as $obj){
                $decoded_obj = json_decode($obj,true);
                array_push($filter_objects,$decoded_obj['id']);
            }
            $data = $data->where(function ($q) use ($filter_objects) {
                $q->whereIn('id',$filter_objects);
            });
        }
        
            

        if($request->start_date && $request->end_date)
        {
            
            $formatted_start_date = Carbon::parse($request->start_date)->format('Y-m-d');
            $formatted_end_date = Carbon::parse($request->end_date)->format('Y-m-d');

            $period = $formatted_start_date. ' 00:00:00'.' - '.$formatted_end_date. ' 23:59:59';

            $data = $data
            ->with('carREports', function($query) use($formatted_start_date, $formatted_end_date){
                $query
                ->where('start_time','>=', $formatted_start_date. ' 00:00:00')
                ->where('end_time','<=', $formatted_end_date. ' 23:59:59');
            });

            // dd($data);

        }

        $data = $data->get()->toArray();

        // dd($data);

        $car_data = new CarReportExport($data,$period);

        // dd($car_data);

        $private_storage_path = storage_path('app' . DIRECTORY_SEPARATOR . 'private'. DIRECTORY_SEPARATOR . 'temp');
        $private_relative_storage_path = 'private' . DIRECTORY_SEPARATOR . 'temp';

        $random_name = rand() . time() . '.xlsx';

        if(!file_exists($private_storage_path)){
            \mkdir($private_storage_path, intval('755',8), true);
        }

        Excel::store($car_data , $private_relative_storage_path . DIRECTORY_SEPARATOR .  $random_name);


        $tempFile = TempFile::create([
            'type' => 'Reports', 
            'random_name' => $random_name, 
            'absolute_path' => $private_storage_path, 
            'mime_type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'path' => $private_relative_storage_path, 
            'filename' => 'Reports.xlsx', 
            'extension' => 'xlsx'
        ]);
        
        $tempUrl = URL::temporarySignedRoute(
            'downloadFile', now()->addMinutes(env('DOWNLOAD_URL_EXPIRE_IN')), ['file' => $tempFile->id]
        );

        return response()->json(['tempUrl' => $tempUrl], 200);
    }
}
