<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\IOFactory;

class parseTypeSheet extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:parse-type-sheet';

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Path to the Excel file
        $fileName = 'doctor intake request form.xlsx';
        $filePath = storage_path($fileName);

        if (!file_exists($filePath)) {
            $this->error('File not found: ' . $filePath);
            return Command::FAILURE;
        }

        // Load the Excel file
        $spreadsheet = IOFactory::load($filePath);
        $worksheet = $spreadsheet->getSheetByName('type');

        if (!$worksheet) {
            $this->error('Sheet2 not found in the Excel file.');
            return Command::FAILURE;
        }

        $objects = [];
        $counter = 1; // Initialize counter

        // Get the highest column number
        $highestColumn = $worksheet->getHighestColumn();
        // Convert the column letter to a number
        $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // Iterate through columns
        for ($col = 1; $col <= $highestColumnIndex; $col += 2) {
            $type = $worksheet->getCellByColumnAndRow($col, 1)->getValue(); // Get the type
            $name = $worksheet->getCellByColumnAndRow($col + 1, 1)->getValue(); // Get the name
            $values = [];

            // Initialize row counter
            $row = 2;

            // Iterate through the values in the column pair using a do-while loop to ensure it executes at least once
            do {
                $keyCell = $worksheet->getCellByColumnAndRow($col, $row);
                $valueCell = $worksheet->getCellByColumnAndRow($col + 1, $row);

                // Check if key and value cells are not empty
                if ($keyCell->getValue() !== null && $valueCell->getValue() !== null) {
                    $key = $keyCell->getValue();
                    $value = $valueCell->getValue();

                    // Add key-value pair to the values array
                    $values[$key] = $value;

                    // Increment row counter
                    $row++;
                } else {
                    // If either key or value cell is empty, exit the loop
                    break;
                }
            } while (true);

            // Add object to the objects array only if type and name are not null and values are not empty
            if ($type !== null && $name !== null && !empty($values)) {
                $objects[$type] = [
                    'type' => $name,
                    'values' => $values
                ];
            }
        }

        // Convert the array to JSON
        $json = json_encode($objects, JSON_PRETTY_PRINT);

        // Save JSON to a file
        $outputFilePath = resource_path('js/views/pages/questionere/type_parse.json');
        file_put_contents($outputFilePath, $json);

        $this->info('JSON data saved to: ' . $outputFilePath);
    }


    // Helper function to get the cell value safely
    private function getCellValue($cell)
    {
        return $cell ? $cell->getValue() : '';
    }
}
