<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\EmlExport;
use ZBateson\MailMimeParser\Message;
use ZBateson\MailMimeParser\Header\HeaderConsts;

class EmlController extends Controller
{
    public function showForm()
    {
        return view('upload-eml'); // Blade view for file upload
    }

public function convert(Request $request)
{
    $request->validate([
        'eml_file' => 'required|file|mimes:eml',
    ]);

    $path = $request->file('eml_file')->move(public_path('eml_files'), $request->file('eml_file')->getClientOriginalName());
    $filePath = public_path('eml_files/' . $request->file('eml_file')->getClientOriginalName());

    if (!file_exists($filePath)) {
        return response()->json(['error' => 'File not found.'], 404);
    }

    $fileContents = file_get_contents($filePath);
    $message = Message::from($fileContents, false);

    // 🟡 Get the HTML body instead of plain text
    $html = $message->getHtmlContent();

    if (!$html) {
        return response()->json(['error' => 'No HTML content found in EML.'], 422);
    }

    // 🟢 Parse the HTML table
    $rows = $this->extractHtmlTableRows($html);

    if (empty($rows)) {
        return response()->json(['error' => 'No table data found in HTML content.'], 422);
    }

    return Excel::download(new EmlExport($rows), 'email.xlsx');
}

    
private function extractHtmlTableRows(string $html): array
{
    libxml_use_internal_errors(true);
    $dom = new \DOMDocument();
    $dom->loadHTML($html);
    $xpath = new \DOMXPath($dom);

    $tables = $xpath->query('//table');
    $finalRows = [];

    foreach ($tables as $table) {
        foreach ($table->getElementsByTagName('tr') as $tr) {
            $row = [];

            foreach ($tr->childNodes as $cell) {
                if ($cell->nodeType !== XML_ELEMENT_NODE) continue;

                if (in_array(strtolower($cell->nodeName), ['td', 'th'])) {
                    $colspan = $cell->getAttribute('colspan') ?: 1;
                    $text = trim($cell->textContent);

                    // Fill in the correct number of cells for colspan
                    for ($i = 0; $i < $colspan; $i++) {
                        $row[] = $text;
                    }
                }
            }

            if (!empty($row)) {
                $finalRows[] = $row;
            }
        }
    }

    return $finalRows;
}

    private function extractTimeCardRows(string $body): array
{
    $lines = explode("\n", $body);
    $rows = [];

    foreach ($lines as $line) {
        if (preg_match('/^\s*(\d{2})\s+([A-Za-z]{2})\s+(.*)$/', $line, $matches)) {
            $date = $matches[1];
            $day = $matches[2];
            $rest = preg_split('/\s+/', trim($matches[3]));

            // Safely extract times (some rows have missing values)
            $inAm = $rest[0] ?? '';
            $outAm = $rest[1] ?? '';
            $inPm = $rest[2] ?? '';
            $outPm = $rest[3] ?? '';
            $otIn = $rest[4] ?? '';
            $otOut = $rest[5] ?? '';
            $total = $rest[6] ?? '';

            $rows[] = [$date, $day, $inAm, $outAm, $inPm, $outPm, $otIn, $otOut, $total];
        }
    }

    return $rows;
}

}
