<?php

namespace App\Http\Controllers;

use App\Models\ClientRequest;
use App\Models\AboutSection;
use App\Models\AgencyNotification;
use App\Models\Message;
use App\Models\NotificationSetting;
use App\Models\Plan;
use App\Models\PortfolioProject;
use App\Models\Service;
use App\Models\Setting;
use App\Models\SystemSetting;
use App\Models\TeamMember;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\View\View;

class PublicController extends Controller
{
    public function home(): View
    {
        return view('public.home', [
            'services' => Service::where('status', 'active')->take(7)->get(),
            'projects' => PortfolioProject::where('status', 'published')->latest()->take(6)->get(),
            'plans' => Plan::where('status', 'active')->take(3)->get(),
            'gtsEnabled' => $this->gtsEnabled(),
        ]);
    }

    public function about(): View
    {
        $sections = Schema::hasTable('about_sections')
            ? AboutSection::where('status', 'active')->orderBy('sort_order')->get()->keyBy('section_key')
            : collect();
        $team = Schema::hasTable('team_members')
            ? TeamMember::where('status', 'active')->orderBy('sort_order')->orderBy('name')->get()
            : collect();

        return view('public.about', [
            'sections' => $sections,
            'team' => $team,
            'projects' => PortfolioProject::where('status', 'published')->latest()->take(3)->get(),
        ]);
    }

    public function services(): View
    {
        return view('public.services', ['services' => Service::latest()->get()]);
    }

    public function order(?Service $service = null): View
    {
        return view('public.order', [
            'selectedService' => $service,
            'services' => Service::where('status', 'active')->orderBy('name')->get(),
        ]);
    }

    public function storeOrder(Request $request): RedirectResponse
    {
        $guest = ! $request->user();
        $rules = [
            'service_id' => ['required', 'exists:services,id'],
            'name' => [$guest ? 'required' : 'nullable', 'string', 'max:255'],
            'email' => [$guest ? 'required' : 'nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'password' => [$guest ? 'required' : 'nullable', 'string', 'min:8', 'confirmed'],
            'title' => ['required', 'string', 'max:255'],
            'details' => ['required', 'string'],
            'deadline' => ['nullable', 'date'],
            'file_path' => ['nullable', 'file', 'mimes:'.SystemSetting::uploadExtensions().',jpg,jpeg,png,webp,pdf,zip', 'max:'.SystemSetting::uploadLimitKilobytes()],
        ];
        $data = $request->validate($rules);
        $service = Service::findOrFail($data['service_id']);

        if ($request->user()) {
            abort_unless($request->user()->role === 'client', 403);
            $user = $request->user();
        } else {
            $existing = User::where('email', $data['email'])->first();
            if ($existing) {
                return redirect()->route('login')->with('status', 'An account already exists with this email. Please login to place the order.');
            }

            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone'] ?? null,
                'password' => Hash::make($data['password']),
                'role' => 'client',
                'client_type' => 'one_time',
                'status' => 'active',
            ]);
            Auth::login($user);
        }

        $path = null;
        if ($request->hasFile('file_path')) {
            $path = $request->file('file_path')->store('one-time-orders', 'public');
        }

        ClientRequest::create([
            'user_id' => $user->id,
            'service_id' => $service->id,
            'request_type' => 'one_time_order',
            'title' => $data['title'],
            'details' => "Service: {$service->name}\nPhone: ".($data['phone'] ?? $user->phone ?? '-')."\n\n".$data['details'],
            'deadline' => $data['deadline'] ?? null,
            'file_path' => $path,
            'status' => 'pending',
        ]);

        if (NotificationSetting::where('notification_type', 'new_request_submitted')->value('dashboard_enabled') ?? true) {
            AgencyNotification::create([
                'title' => 'New one-time service order',
                'body' => $user->name.' ordered '.$service->name.'.',
                'audience' => 'admin',
                'status' => 'unread',
            ]);
        }

        return redirect()->route('client.requests')->with('status', 'Your service order is submitted. Your client portal is ready.');
    }

    public function portfolio(): View
    {
        return view('public.portfolio', ['projects' => PortfolioProject::latest()->get()]);
    }

    public function pricing(): View
    {
        return view('public.pricing', ['plans' => Plan::latest()->get()]);
    }

    public function gts(): View
    {
        abort_unless($this->gtsEnabled(), 404);

        return view('public.gts', [
            'catalog' => $this->gtsCatalog(),
            'whatsappNumber' => '03068665907',
        ]);
    }

    public function contact(): View
    {
        return view('public.contact');
    }

    public function sendContact(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'subject' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string'],
        ]);

        Message::create([
            'subject' => 'Website: '.$data['subject'],
            'body' => "From: {$data['name']} <{$data['email']}>\n\n{$data['message']}",
            'status' => 'open',
        ]);

        return back()->with('status', 'Your message has been sent. We will contact you soon.');
    }

    private function gtsEnabled(): bool
    {
        return Setting::valueFor('gts_landing_enabled', '1') === '1';
    }

    private function gtsCatalog(): array
    {
        return [
            ['TikTok Likes', 'Fast social proof for posts', '500 likes', 'Rs. 90', 'likes'],
            ['TikTok Followers', 'Real active follower boosts', '100 followers', 'Rs. 85', 'followers'],
            ['TikTok Views', 'High retention reach packages', '1K views', 'Rs. 35', 'views'],
            ['TikTok Comments', 'Audience conversation packs', '100 comments', 'Rs. 192', 'comments'],
            ['Instagram Services', 'Followers, likes, views, and comments', '1K followers', 'Rs. 1,299', 'instagram'],
            ['Facebook Services', 'Page/profile followers and post reactions', '1K followers', 'Rs. 410', 'facebook'],
            ['WhatsApp Poll Votes', 'Poll vote delivery support', '100 votes', 'Rs. 250', 'whatsapp'],
            ['UK Account', 'Premium account sourcing lane', 'Verified account', 'Rs. 999', 'account'],
        ];
    }
}
