<?php

namespace App\Services;

use App\Models\EmployeeCard;
use Barryvdh\DomPDF\Facade\Pdf;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use ZipArchive;

class CardPdfService
{
    /**
     * Generate PDF for a single employee card.
     * Card size: CR80 (85.6mm x 54mm)
     */
    public function generateCardPdf(EmployeeCard $card): string
    {
        $user = $card->user;
        $company = $card->company;

        // Generate QR code as SVG (doesn't require imagick)
        $qrData = $card->qr_data;
        $qrCode = QrCode::format('svg')
            ->size(200)
            ->errorCorrection('H')
            ->margin(1)
            ->generate($qrData);
        $qrBase64 = base64_encode($qrCode);

        // Get user avatar as base64 if exists (stored directly in public folder)
        $avatarBase64 = null;
        if ($user->avatar) {
            $avatarPath = public_path($user->avatar);
            if (file_exists($avatarPath)) {
                $avatarBase64 = base64_encode(file_get_contents($avatarPath));
            }
        }

        // Get company logo as base64 if exists (stored directly in public folder)
        $logoBase64 = null;
        if ($company->logo) {
            $logoPath = public_path($company->logo);
            if (file_exists($logoPath)) {
                $logoBase64 = base64_encode(file_get_contents($logoPath));
            }
        }

        $pdf = Pdf::loadView('pdf.employee-card', [
            'card' => $card,
            'user' => $user,
            'company' => $company,
            'qrBase64' => $qrBase64,
            'avatarBase64' => $avatarBase64,
            'logoBase64' => $logoBase64,
        ]);

        // CR80 card size in PORTRAIT: 54mm x 85.6mm = 153.07 x 242.65 points
        $pdf->setPaper([0, 0, 153.07, 242.65], 'portrait');

        return $pdf->output();
    }

    /**
     * Generate batch PDF with multiple cards (A4 layout, 2x4 cards per page).
     */
    public function generateBatchPdf(array $cardIds): string
    {
        $cards = EmployeeCard::whereIn('id', $cardIds)
            ->with(['user', 'company'])
            ->get();

        $cardsData = $cards->map(function ($card) {
            $qrCode = QrCode::format('svg')
                ->size(150)
                ->errorCorrection('H')
                ->margin(1)
                ->generate($card->qr_data);

            $avatarBase64 = null;
            if ($card->user->avatar) {
                $avatarPath = public_path($card->user->avatar);
                if (file_exists($avatarPath)) {
                    $avatarBase64 = base64_encode(file_get_contents($avatarPath));
                }
            }

            $logoBase64 = null;
            if ($card->company->logo) {
                $logoPath = public_path($card->company->logo);
                if (file_exists($logoPath)) {
                    $logoBase64 = base64_encode(file_get_contents($logoPath));
                }
            }

            return [
                'card' => $card,
                'user' => $card->user,
                'company' => $card->company,
                'qrBase64' => base64_encode($qrCode),
                'avatarBase64' => $avatarBase64,
                'logoBase64' => $logoBase64,
            ];
        });

        $pdf = Pdf::loadView('pdf.employee-cards-batch', [
            'cards' => $cardsData,
        ]);

        $pdf->setPaper('a4', 'portrait');

        return $pdf->output();
    }

    /**
     * Generate individual PDFs and zip them together.
     */
    public function generateCardsZip(array $cardIds): string
    {
        $tempDir = storage_path('app/temp/cards-' . now()->timestamp);
        if (!file_exists($tempDir)) {
            mkdir($tempDir, 0755, true);
        }

        $cards = EmployeeCard::whereIn('id', $cardIds)
            ->with(['user', 'company'])
            ->get();

        $zipPath = $tempDir . '/kartu-karyawan-' . now()->format('YmdHis') . '.zip';
        $zip = new ZipArchive();

        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            throw new \Exception('Gagal membuat file ZIP');
        }

        foreach ($cards as $card) {
            $pdfContent = $this->generateCardPdf($card);
            $fileName = "kartu-{$card->card_number}.pdf";
            $zip->addFromString($fileName, $pdfContent);
        }

        $zip->close();

        // Clean up temp directory after some time (or use a queue job)
        // For now, we'll just return the path

        return $zipPath;
    }

    /**
     * Get card dimensions in various units.
     */
    public function getCardDimensions(string $unit = 'mm'): array
    {
        $dimensions = [
            'mm' => ['width' => 85.6, 'height' => 54],
            'cm' => ['width' => 8.56, 'height' => 5.4],
            'in' => ['width' => 3.37, 'height' => 2.13],
            'pt' => ['width' => 242.65, 'height' => 153.07],
        ];

        return $dimensions[$unit] ?? $dimensions['mm'];
    }
}
