<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Program;
use App\Services\AuditLogService;
use App\Services\QrCodeService;
use Illuminate\Support\Str;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\View\View;

class QrCodeController extends Controller
{
    public function __construct(private QrCodeService $qrCodeService) {}

    public function show(Program $program): View
    {
        $qrCode = $program->qrCodes()->where('is_active', true)->latest()->first();

        return view('admin.programs.qr', compact('program', 'qrCode'));
    }

    public function generate(Program $program): RedirectResponse
    {
        $qrCode = $this->qrCodeService->generateForProgram($program);

        AuditLogService::log('qrcode.generated', $program);

        return redirect()
            ->route('admin.programs.qr.show', $program)
            ->with('success', 'QR Code berjaya dijana.');
    }

    public function download(Program $program): Response|RedirectResponse
    {
        $qrCode = $program->qrCodes()->where('is_active', true)->latest()->first();

        if (! $qrCode) {
            return back()->with('error', 'QR Code belum dijana.');
        }

        $png      = $this->qrCodeService->getRawPng($qrCode);
        $filename = 'QR_' . Str::slug($program->title) . '_' . now()->format('Ymd') . '.png';

        return response($png, 200, [
            'Content-Type'        => 'image/png',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    public function deactivate(Program $program): RedirectResponse
    {
        $program->qrCodes()->where('is_active', true)->update(['is_active' => false]);

        AuditLogService::log('qrcode.deactivated', $program);

        return back()->with('success', 'QR Code berjaya dinyahaktifkan.');
    }
}
