<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Invoice;
use Illuminate\Support\Facades\File;

class InvoiceExportService
{
    /**
     * @return array{url: string, format: string, path: string}
     */
    public function export(Invoice $invoice, string $format = 'pdf'): array
    {
        $invoice->loadMissing(['items', 'project', 'user']);

        $dir = public_path('files/invoices/' . $invoice->id);
        File::ensureDirectoryExists($dir);

        $format = strtolower($format) === 'xlsx' ? 'xlsx' : 'pdf';

        if ($format === 'xlsx') {
            $filename = 'invoice-' . $invoice->id . '.csv';
            $path = $dir . '/' . $filename;
            File::put($path, $this->toCsv($invoice));
        } else {
            $filename = 'invoice-' . $invoice->id . '.html';
            $path = $dir . '/' . $filename;
            File::put($path, $this->toHtml($invoice));
        }

        return [
            'url' => url('files/invoices/' . $invoice->id . '/' . $filename),
            'format' => $format === 'xlsx' ? 'csv' : 'html',
            'path' => 'files/invoices/' . $invoice->id . '/' . $filename,
        ];
    }

    private function toCsv(Invoice $invoice): string
    {
        $lines = [];
        $lines[] = $this->csvRow(['شماره', 'عنوان', 'نوع', 'وضعیت', 'مبلغ', 'تاریخ صدور']);
        $lines[] = $this->csvRow([
            $invoice->number ?? $invoice->id,
            $invoice->title,
            $invoice->type,
            $invoice->status,
            (string) $invoice->total,
            optional($invoice->issued_at)->toDateString(),
        ]);
        $lines[] = '';
        $lines[] = $this->csvRow(['ردیف', 'شرح', 'تعداد', 'مبلغ واحد', 'جمع']);

        foreach ($invoice->items ?? [] as $index => $item) {
            $lines[] = $this->csvRow([
                (string) ($index + 1),
                $item->title ?? $item->name ?? '',
                (string) ($item->quantity ?? 1),
                (string) ($item->unit_price ?? 0),
                (string) ($item->total ?? $item->amount ?? 0),
            ]);
        }

        return implode("\n", $lines);
    }

    private function toHtml(Invoice $invoice): string
    {
        $title = e($invoice->title ?? ('فاکتور #' . $invoice->id));
        $number = e((string) ($invoice->number ?? $invoice->id));
        $total = number_format((int) $invoice->total);
        $status = e((string) $invoice->status);
        $project = e((string) ($invoice->project?->name ?? '-'));
        $user = e((string) ($invoice->user?->getFilamentName() ?? $invoice->user?->cellphone ?? '-'));
        $issued = e((string) optional($invoice->issued_at)->toDateString());

        $rows = '';
        foreach ($invoice->items ?? [] as $index => $item) {
            $rows .= '<tr>'
                . '<td>' . ($index + 1) . '</td>'
                . '<td>' . e((string) ($item->title ?? $item->name ?? '')) . '</td>'
                . '<td>' . e((string) ($item->quantity ?? 1)) . '</td>'
                . '<td>' . number_format((int) ($item->unit_price ?? 0)) . '</td>'
                . '<td>' . number_format((int) ($item->total ?? $item->amount ?? 0)) . '</td>'
                . '</tr>';
        }

        return <<<HTML
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>{$title}</title>
  <style>
    body { font-family: Tahoma, sans-serif; padding: 24px; color: #111; }
    h1 { font-size: 20px; }
    table { width: 100%; border-collapse: collapse; margin-top: 16px; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: right; }
    th { background: #f5f5f5; }
  </style>
</head>
<body>
  <h1>{$title}</h1>
  <p>شماره: {$number}</p>
  <p>پروژه: {$project}</p>
  <p>کاربر: {$user}</p>
  <p>وضعیت: {$status}</p>
  <p>تاریخ صدور: {$issued}</p>
  <p>مبلغ کل: {$total} تومان</p>
  <table>
    <thead>
      <tr><th>#</th><th>شرح</th><th>تعداد</th><th>مبلغ واحد</th><th>جمع</th></tr>
    </thead>
    <tbody>{$rows}</tbody>
  </table>
</body>
</html>
HTML;
    }

    /**
     * @param  list<string|null>  $cols
     */
    private function csvRow(array $cols): string
    {
        return implode(',', array_map(function (?string $value) {
            $value = (string) $value;
            $value = str_replace('"', '""', $value);

            return '"' . $value . '"';
        }, $cols));
    }
}
