<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Employee\SchEmployee;
use App\Models\Employee\SchEmployeeService;
use App\Models\Services\SchServices;
use App\Models\Settings\CmnBranch;
use SplFileObject;

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

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

    /**
     * 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 1;
        }

        $csvFile = new SplFileObject($file, 'r');
        $csvFile->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);

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

        foreach ($csvFile as $row) {
            // Skip empty rows
            if (empty(array_filter($row))) {
                continue;
            }

            if ($isFirstRow) {
                $services = array_slice($row, 5);
                foreach ($services as $service) {
                    $serviceData[] = SchServices::where('title', $service)->select('id')->first()->id;
                }
                $isFirstRow = false;
                continue; // Skip the first row (header)
            }

            // Ensure row has enough data
            if (count($row) < 6) {
                continue;
            }

            // Process each row of the CSV file
            $name = $row[0];
            $empId = $row[1];
            $gender = ($row[3] == 'M') ? 1 : (($row[3] == 'F') ? 2 : null);
            $empGender = $gender;
            $branchCode = null;

            // Ensure the row is valid before processing
            if (!isset($name, $empId, $empGender)) {
                continue;
            }

            // Split the employee data starting from index 6
            $employeeData = array_slice($row, 5);

            // For debugging purposes, check what employeeData contains
            // dd($employeeData);

            // Create a single record with all the necessary data
            $data = [
                'full_name' => $name,
                'image_url' => 'img/user_default.jpeg',
                'employee_id' => $empId,
                'cmn_branch_id' => CmnBranch::where('branch_code', $row[2])->select('id')->first()->id,
                'email_address' => 'test@gmail.com', // Placeholder email, replace as necessary
                'gender' => $empGender,
                'status' => 1,
                'created_by' => 1,
            ];
            //dd(CmnBranch::where('branch_code', $row[2])->select('id')->first()->id);
            $newEmployee = SchEmployee::updateOrCreate(
                ['employee_id' => $empId], // Unique identifier to find existing record
                $data // Data to update or create
            );

            if ($newEmployee->wasRecentlyCreated) {
                // Insert additional attributes if they exist
                foreach ($employeeData as $key => $value) {
                    if ($value == 'Y') {
                        // Example of using both $serviceData and $employeeData
                        $serviceId = $serviceData[$key]; // Corresponding service ID
                        // Perform the necessary action, e.g., save to a pivot table or another model
                        // Example:
                        SchEmployeeService::create(['sch_employee_id' => $newEmployee->id, 'sch_service_id' => $serviceId, 'status' => 1]);
                    }
                }
            } else {
                // The record was updated
                foreach ($employeeData as $key => $value) {
                    $serviceId = $serviceData[$key];               
                    if ($value == 'Y') {
                        // Insert or update logic
                        SchEmployeeService::updateOrCreate(
                            ['sch_employee_id' => $newEmployee->id, 'sch_service_id' => $serviceId],
                            ['status' => 1]
                        );
                    } elseif ($value == 'N') {
                        // Delete corresponding record
                        SchEmployeeService::where('sch_employee_id', $newEmployee->id)
                            ->where('sch_service_id', $serviceId)
                            ->delete();
                    }
                }
            }

            if ($branchCode === null || ($branchCode !== null && $branchCode !== $row[2])) {
                $branchCode = $row[2];
                CmnBranch::where('branch_code', $branchCode)->update(['status' => 1]);
            }
        }

        $this->info('CSV data processed successfully.');
        return 0;
    }


}
