<?php

namespace App\Exports;

use App\Models\Ticket;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class TicketReportExport implements FromView
{
    
    public function view(): View
    {
        
        $from = Carbon::parse(sprintf(
            '%s 00:00',
            request()->query('from', Carbon::now()->toDateString())
        ));
        $to = Carbon::parse(sprintf(
            '%s 23:59:59',
            request()->query('to', Carbon::now()->toDateString())
        ));
        
               $qb = Ticket::withoutGlobalScope('status')->with('segment.booking')->with('transactions',function($query) use($from, $to){
               $query->whereBetween('created_at', [$from, $to]);
            })->where('ticket_status','!=','V')->where(function ($query) use($from, $to) {
                $query->whereBetween('created_at', [$from, $to])
                      ->orWhereBetween('updated_at', [$from, $to]);
            });
            
        if(auth()->user()->office->is_admin===1 &&auth()->user()->isAdmin()){
            
            if(request()->query('office_id')){
                $qb->whereHas('segment.booking',function($query){
                   $query->where('office_id',request()->query('office_id'));
                });
            } 
        }
        else{
              $qb->whereHas('segment.booking',function($query){
              $query->where('office_id',auth()->user()->office->id);
            });
            
           
        }
        
 
        return view('ticketReports.exports', [
            'tickets' => $qb->get()
        ]);
    }
}