<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ProfileModel;
use App\Models\QRCodeModel;
use App\Models\ActivityLogModel;
use App\Libraries\QRCodeGenerator;

/**
 * QRCodeController — generate, preview, and download QR codes.
 * All uploads stored in public/uploads/ for direct web access.
 */
class QRCodeController extends BaseController
{
    private ProfileModel     $profileModel;
    private QRCodeModel      $qrModel;
    private ActivityLogModel $logModel;
    private QRCodeGenerator  $qrGenerator;

    public function __construct()
    {
        $this->profileModel  = new ProfileModel();
        $this->qrModel       = new QRCodeModel();
        $this->logModel      = new ActivityLogModel();
        $this->qrGenerator   = new QRCodeGenerator();
    }

    // ----------------------------------------------------------------
    // GET /admin/qrcode  — list all QR codes
    // ----------------------------------------------------------------
    public function index(): string
    {
        $profiles = $this->profileModel
                         ->select('profiles.id, profiles.name, profiles.slug, profiles.is_active,
                                   profiles.profile_photo, profiles.designation, profiles.company_name,
                                   qr_codes.id AS qr_id, qr_codes.file_path AS qr_file,
                                   qr_codes.generated_at, qr_codes.qr_url')
                         ->join('qr_codes', 'qr_codes.profile_id = profiles.id', 'left')
                         ->orderBy('profiles.created_at', 'DESC')
                         ->findAll();

        return $this->render('admin/qrcode/index', [
            'title'    => lang('Admin.qr_codes'),
            'profiles' => $profiles,
        ]);
    }

    // ----------------------------------------------------------------
    // POST /admin/qrcode/generate/:profileId
    // ----------------------------------------------------------------
    public function generate(int $profileId)
    {
        $profile = $this->profileModel->find($profileId);
        if (! $profile) {
            $this->flashError(lang('Admin.user_not_found'));
            return redirect()->to(site_url('admin/qrcode'));
        }

        // QR base URL priority:
        //  1. qr.baseURL from .env  (e.g. http://nityam.in/profile)
        //  2. qr_base_url key in the settings DB table
        //  3. Fallback: derive from current request host
        $envBase     = env('qr.baseURL');
        $settingBase = model('App\Models\SettingsModel')->getSetting('qr_base_url');

        if (! empty($envBase)) {
            $qrUrl = rtrim($envBase, '/') . '/' . $profile['slug'];
        } elseif (! empty($settingBase)) {
            $qrUrl = rtrim($settingBase, '/') . '/' . $profile['slug'];
        } else {
            $req      = service('request');
            $scheme   = $req->isSecure() ? 'https' : 'http';
            $host     = $req->getServer('HTTP_HOST');
            $basePath = rtrim(dirname($req->getServer('SCRIPT_NAME'), 2), '/\\');
            $qrUrl    = $scheme . '://' . $host . $basePath . '/profile/' . $profile['slug'];
        }

        // Profile photo used automatically as QR background — no user options needed
        $photoPath = null;
        if (! empty($profile['profile_photo'])) {
            $candidate = FCPATH . 'uploads/' . ltrim($profile['profile_photo'], '/');
            if (file_exists($candidate)) {
                $photoPath = $candidate;
            }
        }

        try {
            $savePath = FCPATH . 'uploads/qrcodes/qr_profile_' . $profileId . '.png';

            $this->qrGenerator->generate([
                'data'       => $qrUrl,
                'save_path'  => $savePath,
                'photo_path' => $photoPath,   // profile photo as dot-style background
                'foreground' => '#000000',
                'background' => '#FFFFFF',
                'size'       => 1200,  // 1200 px → 300 DPI visiting-card quality (≈4 cm at 300 dpi)
                'margin'     => 0,    // margin computed inside generator from module count
            ]);

            $this->qrModel->upsert($profileId, [
                'file_path'  => 'qrcodes/qr_profile_' . $profileId . '.png',
                'qr_url'     => $qrUrl,
                'has_logo'   => 0,
                'logo_path'  => null,
                'foreground' => '#000000',
                'background' => '#FFFFFF',
            ]);

            $this->logModel->log('generate', 'qr_codes', $profileId,
                'Generated QR for: ' . $profile['name']);

            $this->flashSuccess(lang('Admin.qr_generated'));
        } catch (\Throwable $e) {
            log_message('error', 'QR generation failed: ' . $e->getMessage());
            $this->flashError(lang('Admin.qr_error') . ': ' . $e->getMessage());
        }

        return redirect()->to(site_url('admin/qrcode'));
    }

    // ----------------------------------------------------------------
    // GET /admin/qrcode/download/:profileId
    // ----------------------------------------------------------------
    public function download(int $profileId)
    {
        $qr = $this->qrModel->getByProfile($profileId);
        if (! $qr || empty($qr['file_path'])) {
            $this->flashError(lang('Admin.qr_not_found'));
            return redirect()->to(site_url('admin/qrcode'));
        }

        $filePath = FCPATH . 'uploads/' . $qr['file_path'];
        if (! file_exists($filePath)) {
            $this->flashError(lang('Admin.qr_file_missing'));
            return redirect()->to(site_url('admin/qrcode'));
        }

        $profile  = $this->profileModel->find($profileId);
        $filename = 'qr_' . slugify($profile['name'] ?? 'profile') . '.png';

        return $this->response
                    ->setHeader('Content-Type', 'image/png')
                    ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
                    ->setBody(file_get_contents($filePath));
    }

    // ----------------------------------------------------------------
    // POST /admin/qrcode/delete/:profileId
    // ----------------------------------------------------------------
    public function delete(int $profileId)
    {
        $qr = $this->qrModel->getByProfile($profileId);
        if ($qr) {
            if (! empty($qr['file_path'])) {
                $path = FCPATH . 'uploads/' . $qr['file_path'];
                if (file_exists($path)) {
                    @unlink($path);
                }
            }
            $this->qrModel->where('profile_id', $profileId)->delete();
            $this->logModel->log('delete', 'qr_codes', $profileId, 'Deleted QR code');
            $this->flashSuccess(lang('Admin.qr_deleted'));
        }
        return redirect()->to(site_url('admin/qrcode'));
    }
}
