<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Models\Employee\SchEmployeeRoster;
use App\Models\Employee\SchEmployee;
use App\Models\Employee\SchShift;
use SplFileObject;

class UploadMonthlyRosterData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:upload-monthly-roster-data {file?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'To upload monthly roster data with csv.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $file = $this->argument('file');

        if (!$file) {
            // If file path is not provided as argument, ask the user to enter the name of the CSV file
            $fileName = $this->ask('Enter the name of the CSV file');

            // Construct the full path to the CSV file
            $file = database_path('csv/' . $fileName);
        }
        
        // Check if the file exists using the full path
        if (!file_exists($file)) {
            $this->error('The specified file does not exist.');
            return;
        }
        //dd('testing', $file);
        $csvFile = new SplFileObject($file, 'r');
        $csvFile->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);

        $csv = $csvFile->fgets();

        $isFirstRow = true; // Flag to detect the first row

        foreach ($csvFile as $row) {
            if ($isFirstRow) {
                $isFirstRow = false;
                continue; // Skip the first row (header)
            }

           // dd($row);
            // Process each row of the CSV file
            // Example: Save each row to the database
            // Assuming CSV structure: column1, column2, column3
            // DB::table('your_table')->insert([
            //     'column1' => $row[0] ?? null,
            //     'column2' => $row[1] ?? null,
            //     'column3' => $row[2] ?? null,
            // ]);

            $monthMap = [
                "January" => 1,
                "February" => 2,
                "March" => 3,
                "April" => 4,
                "May" => 5,
                "June" => 6,
                "July" => 7,
                "August" => 8,
                "September" => 9,
                "October" => 10,
                "November" => 11,
                "December" => 12,
            ];
            
            // Convert month name to number
            $monthNumber = $row[0];
            $month = $monthMap[$monthNumber] ?? null;
            $year = $row[1];
            $branchId = $row[2];
            $employeeId = $row[3];

            $schEmployeeId = schEmployee::where('employee_id', $employeeId)->value('id');
            //dd($schEmployeeId, $employeeId);
            $rosterData = $this->split_array_at_index($row, 6);

            //dd($rosterData);
            $day = 1;
            foreach ($rosterData as $value) {
                // Determine the date using Carbon and format it as a string
                $date = Carbon::createFromFormat('Y-m-d', $year.'-'.$month.'-'.$day)->format('Y-m-d');
            
                // Fetch shift data
                $shiftName = schShift::where('legends', $value)->value('name');
                $shiftId = schShift::where('legends', $value)->value('id');
                $isOffday = !$shiftName;
            
                // Data for matching the record
                $matchData = [
                    'sch_employee_id' => $schEmployeeId,
                    'start_date' => $date,
                    'end_date' => $date
                ];
            
                // Data for updating or creating the record
                $updateData = [
                    'title' => $shiftName ? $shiftName : 'Off day',
                    'sch_shift_id' => $shiftId,
                    'is_offday' => $isOffday,
                    'created_by' => 1,
                    'updated_by' => 1,
                    'created_at' => now(),
                    'updated_at' => now()
                ];
            
                // Log the matchData and updateData for debugging
                \Log::info('Match Data:', $matchData);
                \Log::info('Update Data:', $updateData);
            
                // Use updateOrCreate to insert or update the record
                $roster = SchEmployeeRoster::updateOrCreate($matchData, $updateData);
            
                // Log the result
                \Log::info('Roster Result:', $roster->toArray());
            
                $day++;
            }
        }
    }

    public function split_array_at_index($arr, $index) {
        $part1 = array_slice($arr, 0, $index); // Elements before index
        $part2 = array_slice($arr, $index);    // Elements from index onwards
        return $part2;
    }
}
