<?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\PrepaidSummary;
use App\Models\Takings;
use App\Models\PrepaidCard;
use Illuminate\Support\Facades\DB;

class CancelPrepaidSummaryJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $prepaidSummaryCode;
    private $originalCode;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            DB::beginTransaction();
            // Delete Taking
            $taking = Takings::where('code', $this->prepaidSummaryCode)->first();
            if (!$taking) {
                return;
            }
            $taking->delete();

            // Cancel prepaid summary
            $summary = PrepaidSummary::where('code', $this->prepaidSummaryCode)->first();
            $summary->cancel_concept = "Movimiento " . $this->originalCode . " Duplicado";
            $summary->save();

            // Return balance
            $card = PrepaidCard::find($summary->prepaid_card_id);
            $card->balance += $summary->amount;
            $card->save();

            // Register a new movement
            $newSummary = PrepaidSummary::create([
                "prepaid_card_id" => $card->id,
                "code" => $this->prepaidSummaryCode,
                "type" => "add",
                "concept" => "Reverso movimiento " . $this->prepaidSummaryCode,
                "amount" => $summary->amount,
                "new_balance" => $card->balance
            ]);
            DB::commit();
            \Log::info("Reverso de movimiento " . $this->prepaidSummaryCode . " realizado exitosamentes");
        } catch(\Exception $e) {
            // Make a Rollback
            DB::rollback();
            \Log::debug($e);
        }
    }
}
