<?php

namespace App\Console\Commands\V2;


use App\Classes\Jobs\Commands\V2\OneTimeBatchProcessEInvoicesV2CommandJob;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Console\Command;
use App\Models\Booking;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;

class OneTimeBatchProcessEInvoicesV2Command extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */

    protected $signature = 'one-time-batch-process-einvoices-command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'One time batch process E-Invoices for July 2025';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        return;

        $startDate = Carbon::create(2025, 7, 1)->startOfDay();
        $endDate = Carbon::create(2025, 7, 31)->endOfDay();

        $bookings = Booking::where('status', ApprovalStatus::COMPLETED)
            ->whereBetween('created_at', [$startDate, $endDate])
            ->get();

        $count = 0;
        foreach ($bookings as $booking) {
            $firstInvoice = $booking->transactions()
                ->whereIn('type', [TransactionType::INVOICE])
                ->withTrashed()
                ->whereBetween('created_at', [$startDate, $endDate])
                ->orderBy('created_at', 'asc')
                ->first();

            $normalInvoice = $booking->documents()->where('document_type', DocumentType::INVOICE)->first();
            $eInvoice = $booking->documents()->where('document_type', DocumentType::EINVOICE)->first();

            // if($firstInvoice && !$normalInvoice && !$eInvoice){
            if(!$firstInvoice && !$normalInvoice && !$eInvoice){
                OneTimeBatchProcessEInvoicesV2CommandJob::dispatch($booking);
                $count++;
                Log::info('Processed: ' . $count);
                Log::info('Booking ID: ' . $booking->marking . ' | created_at: ' . $booking->created_at);
            }
        }
    }
}
