<?php

namespace App\Jobs;

use App\Models\Refund;
use App\Models\Ticket;
use App\Models\Service;
use App\Models\Transaction;
use App\Traits\Currencies;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class RefundBooking implements ShouldQueue
{
    use Dispatchable, Queueable, SerializesModels, Currencies;
    private $ticket;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($ticket)
    {
        $this->ticket = $ticket;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
       $amount_refund=Transaction::where('ticket_id',  $this->ticket->id)->where('amount','!=',0)->first();
       if($amount_refund){
            $value=$amount_refund->amount;
         
       }
       else{
            $value=0;
       }
        // dd( $amount_refund) ;
        $account = auth()->user()->office->account;
        $date = $this->ticket->created_at;

            $this->ticket->ticket_status = Ticket::STATE_‫‪VOID‬‬;
     
           $amount=0;
           $amout_transaction=0;
        
      

       
        DB::transaction(function () use ($account,$amount,$amout_transaction,$amount_refund,$value) {
            $this->ticket->save();

            Refund::create([
                'ticket_id' => $this->ticket->id,
                'amount' => $amount,
                'currency_code' => $account->currency_code
            ]);

            Transaction::create([
                'account_id' => $account->id,
                'ticket_id' => $this->ticket->id,
                'category' => Transaction::CATEGORY_TICKET,
                'paid_at' => now(),
                'balance' =>(auth()->user()->office->account->balance - $amout_transaction ) +($value *-1) ,

                'amount' => $amout_transaction,
                'type' => Transaction::TYPE_INCOME,
                'currency_code' => $account->currency_code
            ]);

            if($this->ticket->segment->tickets->count()<1){
                $this->ticket->segment->segment_status= $this->ticket->ticket_status;
                $this->ticket->segment->save();
            }
            if($this->ticket->segment->booking->tickets->count()<1){
                $this->ticket->segment->booking->status= $this->ticket->ticket_status;
                $this->ticket->segment->booking->save();
            }

        });
        
  
           $account_user=auth()->user()->office->account;
           $account_user->balance +=$value *-1;
           $account_user->save();

               return $this->ticket;
    }


}
