<?php

namespace Modules\User\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\User\Services\MemberDigitalCardService;
use Symfony\Component\HttpFoundation\Response;

class MemberDigitalCardController extends Controller
{
    public function __construct(
        protected MemberDigitalCardService $memberDigitalCardService
    ) {}

    public function download(Request $request): Response|JsonResponse
    {
        $validated = $request->validate([
            'side' => 'sometimes|in:depan,belakang',
        ]);

        $user = $request->user();
        $side = $validated['side'] ?? 'depan';

        if ($user->status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => 'Kad digital hanya tersedia untuk anggota aktif.',
                'code' => 'digital_card_inactive',
                'data' => null,
            ], 403);
        }

        try {
            $png = $this->memberDigitalCardService->renderPng($user, $side);
            $memberNumber = $user->member_number ?: 'anggota';
            $filename = sprintf('kad-digital-%s-%s.png', $memberNumber, $side);

            return response($png, Response::HTTP_OK, [
                'Content-Type' => 'image/png',
                'Content-Disposition' => 'attachment; filename="'.$filename.'"',
                'Cache-Control' => 'no-store, private',
            ]);
        } catch (\Throwable $exception) {
            Log::error('Failed to render member digital card.', [
                'user_id' => $user->id,
                'side' => $side,
                'message' => $exception->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Gagal menjana kad digital. Sila cuba lagi.',
                'code' => 'digital_card_render_failed',
                'data' => null,
            ], 500);
        }
    }
}
