<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use Illuminate\Support\Facades\Cache;
use App\Models\BasicInfo;
use App\Models\Slug;
use App\Models\VCardView;
class VCardController extends Controller
{
    private $users = [
        'vigneshwaran' => [
            'name' => 'Vigneshwaran Pakirisamy',
            'title' => 'Web Developer',
            'profileImage' => 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop&crop=face',
            'viewCount' => 100,
            'contact' => [
                'address' => '2nd Street, Arumbakkam, Chennai 600029',
                'phones' => ['+91 84185 29635', '+91 81228 21611'],
                'emails' => ['rpvigneshwaran@gmail.com', 'vigneshwaran@innoblitz.in'],
            ],
            'socials' => [
                ['platform' => 'whatsapp', 'icon' => 'fab fa-whatsapp', 'url' => '#'],
                ['platform' => 'linkedin', 'icon' => 'fab fa-linkedin-in', 'url' => '#'],
                ['platform' => 'github', 'icon' => 'fab fa-github', 'url' => '#'],
                ['platform' => 'instagram', 'icon' => 'fab fa-instagram', 'url' => '#'],
                ['platform' => 'twitter', 'icon' => 'fab fa-twitter', 'url' => '#'],
            ],
            'sliderImages' => [
                'https://images.unsplash.com/photo-1517077304055-6e89abbf09b0?w=400&h=300&fit=crop',
                'https://images.unsplash.com/photo-1497366216548-37526070297c?w=400&h=300&fit=crop',
                'https://images.unsplash.com/photo-1497366216548-37526070297c?w=400&h=300&fit=crop',
            ],
            'about' => 'I am a passionate web developer with expertise in Laravel and Vue.js.',
            'education' => [
                ['degree' => 'B.Sc. Computer Science', 'institution' => 'Example University', 'year' => '2018-2021'],
            ],
            'experience' => [
                ['role' => 'Web Developer', 'company' => 'Innoblitz Technologies', 'year' => '2021-Present'],
            ],
            'resume' => [
                'file' => '/path/to/resume.pdf',
            ],
        ],
        'ramya' => [
            'name' => 'Ramya',
            'title' => 'Designer',
            'profileImage' => 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=150&h=150&fit=crop&crop=face',
            'viewCount' => 50,
            'contact' => [
                'address' => 'Some Address, City',
                'phones' => ['+91 12345 67890'],
                'emails' => ['ramya@example.com'],
            ],
            'socials' => [
                ['platform' => 'linkedin', 'icon' => 'fab fa-linkedin-in', 'url' => '#'],
                ['platform' => 'instagram', 'icon' => 'fab fa-instagram', 'url' => '#'],
            ],
            'sliderImages' => [
                'https://images.unsplash.com/photo-1517077304055-6e89abbf09b0?w=400&h=300&fit=crop',
            ],
            'about' => 'Creative designer with a passion for UI/UX.',
            'education' => [
                ['degree' => 'BFA Design', 'institution' => 'Design University', 'year' => '2019-2022'],
            ],
            'experience' => [
                ['role' => 'UI Designer', 'company' => 'Design Studio', 'year' => '2022-Present'],
            ],
            'resume' => [
                'file' => '/path/to/ramya-resume.pdf',
            ],
        ],
    ];

    public function home($slug)
    {
        $user = $this->getUserData($slug);

        $this->incrementViewCount($user);
        $theme = $user ? $user->user->theme : null;
        return Inertia::render('Home', [
            'user' => $user,
            'theme' => $theme,
            'slug' => $slug,
        ]);
    }

    public function about($slug)
    {
        $user = $this->getUserData($slug);
        //$this->incrementViewCount($user);
        $theme = $user ? $user->user->theme : null;
        return Inertia::render('About', [
            'user' => $user,
            'theme' => $theme,
        ]);
    }

    public function education($slug)
    {
        $user = $this->getUserData($slug);
        $this->incrementViewCount($user);
        $theme = $user ? $user->user->theme : null;
        $education = $user ? $user->education : [];
        return Inertia::render('Education', [
            'user' => $user,
            'theme' => $theme,
            'education' => $education,
        ]);
    }

    public function experience($slug)
    {
        $user = $this->getUserData($slug);
        $this->incrementViewCount($user);
        $theme = $user ? $user->user->theme : null;
        $experience = $user ? $user->experience : [];
        return Inertia::render('Experience', [
            'user' => $user,
            'theme' => $theme,
            'experience' => $experience,
        ]);
    }

    public function resume($slug)
    {
        $user = $this->getUserData($slug);
        $this->incrementViewCount($user);
        $theme = $user ? $user->user->theme : null;
        return Inertia::render('Resume', [
            'user' => $user,
            'theme' => $theme,
            'resume' => $user['resume'],
        ]);
    }

    private function incrementViewCount($user)
    {
        if (!$user || !$user->user_id) return;

        $ip = request()->ip();
        $existing = VCardView::where('user_id', $user->user_id)->where('ip_address', $ip)->exists();

        if (!$existing) {
            $user->basicInfo->increment('view_count');
            VCardView::create([
                'user_id' => $user->user_id,
                'ip_address' => $ip,
            ]);
        }
    }

    private function getUserData($slug)
    {
        $cacheKey = 'slug_data_' . $slug;
        $cachedData = Cache::get($cacheKey);

        if ($cachedData && isset($cachedData->basicInfo) && $cachedData->basicInfo->is_new_update == 'false') {
            \Log::info('Using cached data for ' . $slug);
            return $cachedData;
        } else {
            $slugData = Slug::with('basicInfo','backgroundImg','socialLink','user.theme','education','experience')->where('slug',$slug)->first();
            \Log::info('Fetched fresh data for ' . $slug . ': ' . json_encode($slugData));
            if ($slugData && $slugData->basicInfo) {
                $slugData->basicInfo->update(['is_new_update' => 'true']);
                Cache::put($cacheKey, $slugData, 3600); // Cache for 1 hour
            }
            return $slugData ? $slugData : null;
        }
    
   
    }
     public function getShareLinks($slug)
    {
        $user = $this->getUserData($slug);

        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        $url = url("/{$slug}");
        $title = $user->name ?? 'My vCard';
        $description = $user->title ?? 'Check out my professional vCard';
        $image = $user->basicInfo->profile_picture ?? '';

        $shareLinks = [
            'facebook' => "https://www.facebook.com/sharer/sharer.php?u=" . urlencode($url) . "&quote=" . urlencode($title),
            'twitter' => "https://twitter.com/intent/tweet?url=" . urlencode($url) . "&text=" . urlencode($title . ' - ' . $description),
            'linkedin' => "https://www.linkedin.com/sharing/share-offsite/?url=" . urlencode($url),
            'whatsapp' => "https://wa.me/?text=" . urlencode($title . ' ' . $url),
            'telegram' => "https://t.me/share/url?url=" . urlencode($url) . "&text=" . urlencode($title),
            'pinterest' => "https://pinterest.com/pin/create/button/?url=" . urlencode($url) . "&media=" . urlencode($image) . "&description=" . urlencode($description),
            'reddit' => "https://www.reddit.com/submit?url=" . urlencode($url) . "&title=" . urlencode($title),
        ];

        return response()->json($shareLinks);
    }

    public function downloadVCard($slug)
    {
        $user = $this->getUserData($slug);
        
        if (!$user || !$user->basicInfo) {
            return response()->json(['error' => 'User data not found'], 404);
        }

        $basicInfo = $user->basicInfo;
        
        $vcard = "BEGIN:VCARD\n";
        $vcard .= "VERSION:3.0\n";
        $vcard .= "FN:" . ($basicInfo->first_name ?? '') . " " . ($basicInfo->last_name ?? '') . "\n";
        $vcard .= "N:" . ($basicInfo->last_name ?? '') . ";" . ($basicInfo->first_name ?? '') . ";;;\n";
        $vcard .= "TITLE:" . ($basicInfo->profession ?? '') . "\n";
        $vcard .= "EMAIL:" . ($basicInfo->personal_email ?? '') . "\n";
        if ($basicInfo->official_email) {
            $vcard .= "EMAIL:" . $basicInfo->official_email . "\n";
        }
        $vcard .= "TEL:" . ($basicInfo->mobile_no ?? '') . "\n";
        if ($basicInfo->mobile_no1) {
            $vcard .= "TEL:" . $basicInfo->mobile_no1 . "\n";
        }
        $vcard .= "ADR:" . ($basicInfo->address ?? '') . "\n";
        $vcard .= "ORG:Your Organization\n";
        $vcard .= "END:VCARD\n";

        $filename = ($basicInfo->first_name ?? 'User') . "_" . ($basicInfo->last_name ?? '') . ".vcf";

        return response($vcard)
            ->header('Content-Type', 'text/vcard')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }
}