<?php

namespace App\Console\Commands;

use App\Jobs\ForecastReadingJob;
use App\Models\Forecast;
use App\Models\ForecastUpload;
use App\Models\Helpers\General;
use App\Models\User;
use DateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ForecastDataReading extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'read:forecast';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            $data = ForecastUpload::query()->where('status', 'not read')->get();
            $error_rows = [];
            $empty_file = false;
            $reading_result = [];
            $my_lotto = [];

            if ($data !== null) {
                foreach ($data as $item) {
                    $spreadsheet = IOFactory::load(storage_path('app/public/ForecastUploads/' . $item->file_name . '.xlsx'));
                    $sheetCount = $spreadsheet->getSheetCount();

                    for ($sheetIndex = 0; $sheetIndex < $sheetCount; $sheetIndex++) {
                        $worksheet = $spreadsheet->getSheet($sheetIndex);
                        $highestRow = $worksheet->getHighestRow();
                        if ($highestRow < 2) {
                            $empty_file = true;
                        }
                        // Start reading from the second row (row 2) to skip the first row (heading)
                        for ($row = 2; $row <= $highestRow; $row++) {
                            $title              =   $worksheet->getCell('A' . $row)->getValue();
                            $message            =   $worksheet->getCell('B' . $row)->getValue();

                            if ($title !== null && $message !== null) {
                                Forecast::create($my_lotto);
                                $item->update([
                                    'status' => 'read'
                                ]);
                            }

                            $file_name = 'forecast_result_' . $item->id . '.txt';

                            General::excel_Reading_Result($error_rows, $file_name, $empty_file);

                            $attachment_path = storage_path('app/ExcelReading/' . $file_name);
                            $user = auth()->user();
                            ForecastReadingJob::dispatch($user, $file_name);
                            // $user = User::query()->where('email', $item->creator_email)->first();

                            //  MembershipCardJob::dispatch($attachment_path, $user);
                        }
                    }
                }
                echo json_encode($my_lotto);
            }
        } catch (\Throwable $th) {
            Log::info('READING EXCEL DATA: === ' . $th->getMessage());
            echo "Sorry, we encountered an error when reading membership excel data";
        }
        // try {
        //     $data = ForecastUpload::query()->where('status', 'not read')->get();
        //     $error_rows = [];
        //     $empty_file = false;
        //     $reading_result = [];
        //     $my_lotto = [];

        //     if ($data !== null) {
        //         foreach ($data as $item) {
        //             $spreadsheet = IOFactory::load(storage_path('app/public/ForecastUploads/' . $item->file_name . '.xlsx'));
        //             $sheetCount = $spreadsheet->getSheetCount();

        //             for ($sheetIndex = 0; $sheetIndex < $sheetCount; $sheetIndex++) {
        //                 $worksheet = $spreadsheet->getSheet($sheetIndex);
        //                 $highestRow = $worksheet->getHighestRow();
        //                 if ($highestRow < 2) {
        //                     $empty_file = true;
        //                 }
        //                 // Start reading from the second row (row 2) to skip the first row (heading)
        //                 for ($row = 2; $row <= $highestRow; $row++) {
        //                     $title              =   $worksheet->getCell('A' . $row)->getValue();
        //                     $banker             =   $worksheet->getCell('B' . $row)->getValue();
        //                     $two_sure           =   $worksheet->getCell('C' . $row)->getValue();
        //                     $three_direct       =   $worksheet->getCell('D' . $row)->getValue();
        //                     $permutations       =   $worksheet->getCell('E' . $row)->getValue();
        //                     $schedule           =   $worksheet->getCell('F' . $row)->getValue();

        //                     // array_push($reading_result, $two_sure);
        //                     if ($title !== null) {
        //                         $my_lotto['title'] = $title;
        //                         array_push($reading_result, $title);
        //                     }
        //                     if ($banker !== null && General::check_banker($banker)) {
        //                         $my_lotto['banker'] = $banker;
        //                         array_push($reading_result, $banker);
        //                     }
        //                     if ($two_sure !== null && count(General::check_two_sure($two_sure)) < 1) {
        //                         $my_lotto['two_sure'] = $two_sure;
        //                         array_push($reading_result, $two_sure);
        //                     }
        //                     if ($three_direct !== null && count(General::check_three_direct($three_direct)) < 1) {
        //                         $my_lotto['three_direct'] = $three_direct;
        //                         array_push($reading_result, $three_direct);
        //                     }
        //                     if ($permutations !== null && count(General::check_permutations($permutations)) < 1) {
        //                         $my_lotto['permutations'] = $permutations;
        //                         array_push($reading_result, $permutations);
        //                     }

        //                     $schedule_check = General::convert_excel_date($schedule);

        //                     if ($schedule_check) {
        //                         if ($schedule !== null) {
        //                             $excelEpoch = new DateTime('1900-01-01'); // Excel's epoch date
        //                             $date = clone $excelEpoch;
        //                             $new_date = $date->modify("+" . ($schedule - 2) . " days")->format('Y:m:d');
        //                             $my_lotto['schedule'] = $new_date;
        //                         }
        //                     }
        //                     if ($title !== null && $schedule_check && count($reading_result) > 0) {
        //                         $forecast = Forecast::query()->where('schedule', $my_lotto['schedule'])->latest()->first() ?? null;
        //                         if ($forecast == null) {
        //                             Forecast::create($my_lotto);
        //                             $item->update([
        //                                 'status' => 'read'
        //                             ]);
        //                         }
        //                     }

        //                     $file_name = time() . '_forecast_result_' . $item->id . '.txt';

        //                     General::excel_Reading_Result($error_rows, $file_name, $empty_file);

        //                     // $attachment_path = storage_path('app/ExcelReading/' . $item->id . '_result.txt');

        //                     // $user = User::query()->where('email', $item->creator_email)->first();

        //                     //  MembershipCardJob::dispatch($attachment_path, $user);
        //                 }
        //             }
        //         }
        //         echo json_encode($my_lotto);
        //     }
        // } catch (\Throwable $th) {
        //     Log::info('READING EXCEL DATA: === ' . $th->getMessage());
        //     echo "Sorry, we encountered an error when reading membership excel data";
        // }
    }
}
