<?php

namespace App\Exports;

use App\Models\Ticket;
use App\Models\Account;
use App\Models\Refund;
use App\Models\Installment;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class BannerReportExport 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())
        ));
        
        $ticket_used =Transaction::whereHas('ticket', function($q){
                $q->where('ticket_status', '=', 'U');
            })->whereBetween('created_at', [$from, $to])->sum('amount');

        $ticket_open =Transaction::whereHas('ticket', function($q){
                $q->where('ticket_status', '=', 'O');
            })->whereBetween('created_at', [$from, $to])->sum('amount');
        
        $office_balance =Account::whereBetween('created_at', [$from, $to])->sum('balance');
        $transfer_success =Installment::whereHas('transfer.transaction', function($q)use($from,$to){
            
          $q->where('status', '=', 'success')->whereBetween('created_at', [$from, $to]);

            })->sum('amount');
        $transfer_pending =Transaction::where('status', '=', 'pending')->whereBetween('created_at', [$from, $to])->sum('amount');
        $refund_amount =Refund::sum('amount');
        
        
        return view('exports', [
            'ticket_used'          =>$ticket_used,
            'ticket_open'          =>$ticket_open,
            'from'                 =>$from,
            'to'                    =>$to,
            'ticket_open'          =>$ticket_open,
            'office_balance'      =>$office_balance,
            'transfer_success'    =>$transfer_success,
            'transfer_pending'    =>$transfer_pending,
            'refund_amount'       =>$refund_amount
        ]);
    }
}