<?php

namespace App\Http\Controllers;

use App\DataTables\RefundDataTable;
use App\Models\Refund;
use App\Models\Office;
use Carbon\Carbon;
use App\Exports\RefundExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class RefundController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    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 = Refund::whereBetween('created_at', [$from, $to]);
               
        if(request()->query('office_id')){
            $qb->whereHas('ticket.segment.booking',function($query){
               $query->where('office_id',request()->query('office_id'));
            });
        }
        $refunds=$qb->paginate(10);
      
   
        
        return view('refunds.index',compact('refunds'));
    }
 
    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Refund  $refund
     * @return \Illuminate\Http\Response
     */
    public function show(Refund $refund)
    {
        return view('refunds.print',['refund'=>$refund]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Refund  $refund
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Refund $refund)
    {
        $refund->status = Refund::STATUS_SUCCESS;
        return $refund->save();
    }
    
       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 RefundExport, $name.'.xlsx');
    }
}
