<?php

namespace App\Http\Controllers;

use App\Exports\TicketReportExport;
use App\Models\Booking;
use App\Models\Office;
use App\Models\Ticket;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class TicketReportController extends Controller
{
    public function index()
    {
        $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(request()->query('office_id')){
            $qb->whereHas('segment.booking',function($query){
               $query->where('office_id',request()->query('office_id'));
            });
        }
        $tickets=$qb->orderBy('updated_at','desc')->paginate(10);
        return view('ticketReports.index', compact('tickets'));
    }

    public function export() 
    {
        $office = Office::find(request()->query('office_id'));
        $name = $office?$office->name:auth()->user()->name;
        $name .= '-'.request()->query('from').'-'.request()->query('to');
        return Excel::download(new TicketReportExport, $name.'.xlsx');
    }

}
