<?php

namespace App\Jobs;

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 App\Models\PrepaidCard;
use App\Models\PrepaidSummary;

class ValidatePrepaidCardMovementsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $card;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::debug("CARNET " . $this->card->code);
        $summaries = $this->card->prepaidSummaries()
                            ->where('prepaid_summaries.created_at', '>', '2022-09-31')
                            ->join('takings', 'prepaid_summaries.code', '=', 'takings.code')
                            ->select('prepaid_summaries.*', 'takings.vehicle_id', 'takings.turn_id')
                            ->get();
        $last = new PrepaidSummary();
        foreach ($summaries as $summary) {
            if ($last->vehicle_id == $summary->vehicle_id
                && $last->amount == $summary->amount
                && $last->concept == $summary->concept
                && $last->turn_id == $summary->turn_id
                && is_null($summary->cancel_concept)
                && $last->created_at > $summary->created_at->modify("-1 minutes")
            ) {
                \Log::debug("REVISAR " . $last->id . ', ' . $summary->id);
            }
            $last = $summary;
        }
        \Log::debug("-----------------------------------------------------");
    }
}
