<?php

namespace App\Controllers;

use App\Models\ProfileModel;
use App\Models\MediaModel;
use App\Models\QRCodeModel;
use App\Models\SectionModel;
use App\Models\SectionItemModel;

/**
 * ProfileController — public-facing digital profile pages.
 *
 * Routes:
 *   GET  /profile/{slug}         → show profile page
 *   GET  /profile/{slug}/vcard   → download .vcf contact card
 */
class ProfileController extends BaseController
{
    private ProfileModel     $profileModel;
    private MediaModel       $mediaModel;
    private QRCodeModel      $qrModel;
    private SectionModel     $sectionModel;
    private SectionItemModel $sectionItemModel;

    public function __construct()
    {
        $this->profileModel      = new ProfileModel();
        $this->mediaModel        = new MediaModel();
        $this->qrModel           = new QRCodeModel();
        $this->sectionModel      = new SectionModel();
        $this->sectionItemModel  = new SectionItemModel();
    }

    // ----------------------------------------------------------------
    // GET /profile/{slug}
    // ----------------------------------------------------------------
    public function show(string $slug): string
    {
        // Sanitise slug
        $slug = preg_replace('/[^a-zA-Z0-9\-_]/', '', $slug);

        // Fetch active profile by slug
        $profile = $this->profileModel
                        ->where('slug', $slug)
                        ->where('is_active', 1)
                        ->where('deleted_at IS NULL')
                        ->first();

        if (! $profile) {
            return $this->notFound($slug);
        }

        // Media
        $videos    = $this->mediaModel->getByProfile($profile['id'], 'video');
        $documents = $this->mediaModel->getByProfile($profile['id'], 'document');
        $gallery   = $this->mediaModel->getByProfile($profile['id'], 'gallery');

        // QR Code
        $qr = $this->qrModel->getByProfile($profile['id']);

        // Custom sections
        $sections   = $this->sectionModel->getByProfile($profile['id']);
        $sectionIds = array_column($sections, 'id');
        $sectionItems = $sectionIds
            ? $this->sectionItemModel->getBySections($sectionIds)
            : [];

        // Profile URL (canonical)
        $profileUrl = $this->buildProfileUrl($slug);

        // vCard download URL
        $vcardUrl = site_url('profile/' . $slug . '/vcard');

        return view('profile/show', [
            'profile'      => $profile,
            'videos'       => $videos,
            'documents'    => $documents,
            'gallery'      => $gallery,
            'qr'           => $qr,
            'sections'     => $sections,
            'sectionItems' => $sectionItems,
            'profileUrl'   => $profileUrl,
            'vcardUrl'     => $vcardUrl,
        ]);
    }

    // ----------------------------------------------------------------
    // GET /profile/{slug}/vcard  — download .vcf file
    // ----------------------------------------------------------------
    public function vcard(string $slug)
    {
        $slug = preg_replace('/[^a-zA-Z0-9\-_]/', '', $slug);

        $profile = $this->profileModel
                        ->where('slug', $slug)
                        ->where('is_active', 1)
                        ->first();

        if (! $profile) {
            return $this->response->setStatusCode(404)->setBody('Profile not found');
        }

        $vcf = $this->buildVCard($profile);

        $filename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $profile['name']) . '.vcf';

        return $this->response
                    ->setHeader('Content-Type', 'text/vcard; charset=UTF-8')
                    ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
                    ->setHeader('Cache-Control', 'no-cache')
                    ->setBody($vcf);
    }

    // ----------------------------------------------------------------
    // Private helpers
    // ----------------------------------------------------------------

    /**
     * Build the canonical public profile URL.
     */
    private function buildProfileUrl(string $slug): string
    {
        $envBase = env('qr.baseURL');
        if (! empty($envBase)) {
            return rtrim($envBase, '/') . '/' . $slug;
        }
        return site_url('profile/' . $slug);
    }

    /**
     * Generate a vCard 3.0 string from a profile array.
     */
    private function buildVCard(array $p): string
    {
        $name    = $p['name']         ?? '';
        $title   = $p['designation']  ?? '';
        $company = $p['company_name'] ?? '';
        $email   = $p['email']        ?? '';
        $mobile  = trim(($p['mobile_country_code'] ?? '') . ' ' . ($p['mobile'] ?? ''));
        $address = $p['address']      ?? '';
        $about   = strip_tags($p['about_us'] ?? '');
        $url     = $this->buildProfileUrl($p['slug']);

        // Photo
        $photoB64 = '';
        if (! empty($p['profile_photo'])) {
            $photoPath = FCPATH . 'uploads/' . ltrim($p['profile_photo'], '/');
            if (file_exists($photoPath)) {
                $type = mime_content_type($photoPath);
                $ext  = strtoupper(pathinfo($photoPath, PATHINFO_EXTENSION));
                if (in_array($type, ['image/jpeg', 'image/png', 'image/webp'])) {
                    $photoB64 = 'PHOTO;ENCODING=b;TYPE=' . $ext . ':'
                              . base64_encode(file_get_contents($photoPath));
                }
            }
        }

        $lines   = [];
        $lines[] = 'BEGIN:VCARD';
        $lines[] = 'VERSION:3.0';
        $lines[] = 'FN:' . $this->vcfEscape($name);
        $lines[] = 'N:' . $this->vcfEscape($name) . ';;;;';

        if ($title)   $lines[] = 'TITLE:'  . $this->vcfEscape($title);
        if ($company) $lines[] = 'ORG:'    . $this->vcfEscape($company);
        if ($mobile)  $lines[] = 'TEL;TYPE=CELL:' . $mobile;
        if ($email)   $lines[] = 'EMAIL;TYPE=INTERNET:' . $email;
        if ($address) $lines[] = 'ADR;TYPE=WORK:;;' . $this->vcfEscape($address) . ';;;;';
        if ($url)     $lines[] = 'URL:'    . $url;
        if ($about)   $lines[] = 'NOTE:'   . $this->vcfEscape($about);
        if ($photoB64) $lines[] = $photoB64;

        // Social links
        $socials = [
            'linkedin'  => $p['linkedin']  ?? null,
            'instagram' => $p['instagram'] ?? null,
            'facebook'  => $p['facebook']  ?? null,
            'twitter'   => $p['twitter']   ?? null,
            'youtube'   => $p['youtube']   ?? null,
        ];
        foreach ($socials as $key => $val) {
            if ($val) $lines[] = 'X-SOCIALPROFILE;TYPE=' . $key . ':' . $val;
        }

        $lines[] = 'END:VCARD';

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

    private function vcfEscape(string $str): string
    {
        return str_replace(["\n", ',', ';', '\\'], ["\\n", '\\,', '\\;', '\\\\'], $str);
    }

    /**
     * Render the 404 profile-not-found page.
     */
    private function notFound(string $slug): string
    {
        $this->response->setStatusCode(404);
        return view('profile/not_found', ['slug' => $slug]);
    }
}
