<?php

namespace App\Jobs;
use App\Models\Refund;
use App\Models\Ticket;
use App\Models\Fees;
use App\Models\FeesRule;
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;
use App\Models\Booking;
use App\Models\Payement;
use Carbon\Carbon;

class ReissuedTicket implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $ticket;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($ticket)
    {
        $this->ticket = $ticket;
     }

    /**
     * Execute the job.
     *
     * @return void
     */
    
    public function handle()
    {
        // 12982
         // dd('iam in reissued ticket'.$this->ticket);   
        $account = auth()->user()->office->account;
         $ticket_num=$this->ticket;
        //  dd($ticket_num);
        // $ticket_num= $ticket_num[0];
         $old_ticket =$ticket_num->old;
 
        $account = auth()->user()->office->account;
        // dd($ticket_num->old_id);
 
             if($ticket_num->is_two_way==1){
            $office_commission=auth()->user()->office->booking_commission /100;
            // $price_first_ticked=$ticket_num->segment->roomType->service->price_two;
            // $price_two_ticked=$old_ticket->segment->roomType->service->price_two;

            ////////////فحص هل للتذكرة الاولى خدمات ام لا وفحص للتذكرة الثانية 
            $price_services_new = 0;
            if($ticket_num->services!=null){
              foreach ($ticket_num->services as $service) {
                $price_services_new +=  $service->price;

              }

            }

            //////////////////
            $price_services_old = 0;

            if($old_ticket->services!=null){
                foreach ($old_ticket->services as $service) {
                  $price_services_old +=  $service->price;
                }
  
              }
            //   dd($price_services_new);
  
                        ///////
            // if($ticket_num->car()->exists()){
            //     $car_price=$ticket_num->ticket->car->car->service->price;
            // }

            ////////////////// حساب التاكس حسب الايام 
        //   الحصول على تاريخ المغادرة 
       $departure_date_time= $old_ticket->segment->cruise->departure_date_time; 
       $now = date('Y-m-d H:i:s');
       $dep_carbon  = Carbon::createFromFormat('Y-m-d H:s:i', $departure_date_time);
       $now_carbon = Carbon::createFromFormat('Y-m-d H:s:i', $now);
        /////95
       $diff_in_hours = $now_carbon->diffInHours($dep_carbon);
    
            ////// الحصول على جميع التاكسات من جدول فيز  
            $keywords = 'reissue';
            $alltax = Fees::where('code','LIKE', '%'.$keywords.'%')
            ->where('status',1)
            ->orderBy('position','asc')
            ->get();
 
            $tax_value = 0;
            foreach($alltax as $f){

                foreach($f->rule as $r){
                    if($r->type =='date_less_or_equal')
                    {
                        $time=$r->configuration;
                        preg_match_all('!\d+!', $time, $matches);
                        $num_of_hours =$matches[0][0];
                        //  $tax_value = $r->tax_percentage->amount;

                        if($diff_in_hours<$num_of_hours){
                            $tax_value = $r->tax_percentage->amount;
                        }
 
                    }
                    


                }

                }
                // dd($tax_value);
            //////////////
             if($ticket_num->price==$old_ticket->price||$ticket_num->price<$old_ticket->price){
                /////////////////اذا كان في خدمات لهذه التذكرة 
                /////////////العملية الحسابية 
                       

                // $remain = (($ticket_num->price +$price_services_new) -($old_ticket->price +$price_services_old))*-1;
                 $remain = 0;
                 ////////حساب الضريبة 
               ///// حساب الضريبة العامة 
               $tax =($old_ticket->price) *$tax_value/100;
            //    dd( $tax);
              ///////////// حساب ضريبة المكتب
               $tax_office =($old_ticket->price) *$ticket_num->tax_office/100;
               //////////حساب عمولة المكتب
               $commission_ticked = $remain *$ticket_num->commission/100;
               /////////////// العملية الحسابية 

               $total =  ($remain+$tax+$tax_office)-$commission_ticked;
                //////////////// خصم المبلغ من حساب الوكالة 
                 $last_balance = $account->balance -$total;
 
                ///////////

                 $payment=  $payment= Payement::create([
                    'booking_id' => $ticket_num->segment->booking_id,
                    'amount' => $total,
                    'currency_code' => $account->currency_code
                ]);


                $transaction = Transaction::create([
                    'account_id' =>$account->id,
                    'ticket_id' => $ticket_num->id,
                    'category' => Transaction::CATEGORY_TICKET,
                    'paid_at' => now(),
                     'balance' =>$last_balance,
                    'amount' => $total,
                    'type' => Transaction::TYPE_EXPENSE,
                    'currency_code' => $account->currency_code
                ]);
 
             }
            else if($ticket_num->price>$old_ticket->price){
/////////////////اذا كان في خدمات لهذه التذكرة 
                /////////////العملية الحسابية 
                $remain = (($ticket_num->price) -($old_ticket->price ))*-1;

                ////////حساب الضريبة 
               ///// حساب الضريبة العامة 
               $tax =($old_ticket->price) *$tax_value/100;
              ///////////// حساب ضريبة المكتب
               $tax_office =($old_ticket->price) *$ticket_num->tax_office/100;
               //////////حساب عمولة المكتب
               $commission_ticked = $remain *$ticket_num->commission/100;
               /////////////// العملية الحسابية 
                $total =  ($remain+$tax+$tax_office)-$commission_ticked;
                //////////////// خصم المبلغ من حساب الوكالة 
                
                $last_balance = $account->balance -$total;
                ///////////
                
                $payment=  $payment= Payement::create([
                    'booking_id' => $ticket_num->segment->booking_id,
                    'amount' => $total,
                    'currency_code' => $account->currency_code
                ]);

                $transaction = Transaction::create([
                    'account_id' =>$account->id,
                    'ticket_id' => $ticket_num->id,
                    'category' => Transaction::CATEGORY_TICKET,
                    'paid_at' => now(),
                     'balance' =>$last_balance,
                    'amount' => $total,
                    'type' => Transaction::TYPE_EXPENSE,
                    'currency_code' => $account->currency_code
                ]);

                // dd($transaction);


            }

        }
        // dd('dasdas');

    }

}

        








