<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Symfony\Component\DomCrawler\Crawler;

class ConvertHtmlToJson extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'convert:html-to-json';
	protected $description = 'Convert HTML files to JSON format';
	
	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * Execute the console command.
	 *
	 * @return int
	 */
	public function handle()
	{
		$inputDirectory = public_path('pages/html');
		$outputDirectory = public_path('pages/json');
		
		if (!File::exists($outputDirectory)) {
			File::makeDirectory($outputDirectory, 0755, true);
		}
		
		$files = File::files($inputDirectory);
		
		foreach ($files as $file) {
			if ($file->getExtension() === 'html') {
				$htmlFilePath = $file->getPathname();
				$jsonFilePath = $outputDirectory . '/' . $file->getFilenameWithoutExtension() . '.json';
				
				try {
					$htmlContent = File::get($htmlFilePath);
					$crawler = new Crawler($htmlContent);
					
					$typeContent = $crawler->filter('h1')->text();
					$subTypeContent = $crawler->filter('h2')->text();
					
					$table = $crawler->filter('table');
					$headerRow = $table->filter('tr')->first();
					$headers = $headerRow->filter('th')->each(function (Crawler $node) {
						return $node->text();
					});
					
					$numHeaders = count($headers);
					$rows = [];
					
					$table->filter('tr')->each(function (Crawler $tr, $i) use (&$rows, $numHeaders) {
						if ($i === 0) return; // Skip header row
						
						$cols = $tr->filter('td')->each(function (Crawler $node) {
							return $node->text();
						});
						
						$numCols = count($cols);
						
						if ($numCols < $numHeaders) {
							$cols = array_merge(array_fill(0, $numHeaders - $numCols, ''), $cols);
						}
						
						$rowData = [];
						foreach ($cols as $index => $col) {
							$rowData['col' . ($index + 1)] = $col;
						}
						
						$rows[] = $rowData;
					});
					
					$data = [
						'type'     => $typeContent,
						'sub_type' => $subTypeContent,
						'header'   => array_combine(array_map(function ($i) {
							return 'col' . ($i + 1);
						}, array_keys($headers)), $headers),
						'rows'     => $rows,
					];
					
					File::put($jsonFilePath, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
					
				} catch (\Exception $e) {
					$this->error("Error processing file {$htmlFilePath}: {$e->getMessage()}");
				}
			}
		}
		
		$this->info('HTML files have been converted to JSON.');
	}
}
