<?php

namespace App\Http\Controllers;

use App\Models\BlogCategory;
use App\Models\BlogPost;
use App\Models\Branch;
use App\Models\Contact;
use App\Models\Package;
use App\Models\Partner;
use App\Models\Service;
use Illuminate\Http\Request;

class FrontendController extends Controller
{
    public function index()
    {

        $branches = Branch::all();
        $partners = Partner::all();
        return view('frontend.home', compact('branches', 'partners'));
    }


    public function branch_details()
    {
        return view('frontend.branch_details');
    }


    public function about()
    {
        return view('frontend.about');
    }



    public function blogs(Request $request)
    {
        // Get categories for sidebar and filtering
        $categories = BlogCategory::withCount([
            'posts' => function ($query) {
                $query->published();
            }
        ])
            ->where('is_active', true)
            ->get();

        // Get featured post (excluding if we're filtering by category)
        $featuredQuery = BlogPost::with(['author', 'category'])
            ->published();

        // Apply category filter if specified
        if ($request->has('category')) {
            $categorySlug = $request->get('category');
            $category = BlogCategory::where('slug', $categorySlug)->first();
            if ($category) {
                $featuredQuery->where('category_id', $category->id);
            }
        }

        $featuredPost = $featuredQuery->featured()
            ->latest()
            ->first();

        // Get recent posts with search and category filtering
        $recentQuery = BlogPost::with(['author', 'category'])
            ->published();

        // Apply search filter
        if ($request->has('search')) {
            $search = $request->get('search');
            $recentQuery->where(function ($query) use ($search) {
                $query->where('title', 'like', '%' . $search . '%')
                    ->orWhere('excerpt', 'like', '%' . $search . '%')
                    ->orWhere('content', 'like', '%' . $search . '%');
            });
        }

        // Apply category filter
        if ($request->has('category')) {
            $categorySlug = $request->get('category');
            $category = BlogCategory::where('slug', $categorySlug)->first();
            if ($category) {
                $recentQuery->where('category_id', $category->id);
            }
        }

        // Exclude featured post if it exists
        if ($featuredPost) {
            $recentQuery->where('id', '!=', $featuredPost->id);
        }

        $recentPosts = $recentQuery->latest()->paginate(6);

        // Get popular posts (most viewed) - with same filters
        $popularQuery = BlogPost::with(['author', 'category'])
            ->published()
            ->orderBy('views', 'desc');

        // Apply category filter to popular posts
        if ($request->has('category')) {
            $categorySlug = $request->get('category');
            $category = BlogCategory::where('slug', $categorySlug)->first();
            if ($category) {
                $popularQuery->where('category_id', $category->id);
            }
        }

        $popularPosts = $popularQuery->take(3)->get();

        return view('frontend.blogs', compact(
            'featuredPost',
            'recentPosts',
            'popularPosts',
            'categories'
        ));
    }



    public function blogShow($slug)
    {
        $post = BlogPost::with(['author', 'category', 'tags'])
            ->where('slug', $slug)
            ->published()
            ->firstOrFail();

        // Increment views
        $post->incrementViews();

        // Get related posts (same category, excluding current)
        $relatedPosts = BlogPost::with(['author', 'category'])
            ->where('category_id', $post->category_id)
            ->where('id', '!=', $post->id)
            ->published()
            ->latest()
            ->take(3)
            ->get();

        // Get categories for sidebar
        $categories = BlogCategory::withCount([
            'posts' => function ($query) {
                $query->published();
            }
        ])
            ->where('is_active', true)
            ->get();

        return view('frontend.blog-single-view', compact('post', 'relatedPosts', 'categories'));
    }

    public function contact()
    {
        $branches = Branch::latest()->get();
        return view('frontend.contact', compact('branches'));
    }


    public function contact_store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'branch' => 'nullable|exists:branches,id',
            'message' => 'required|string|min:10|max:2000',
        ]);

        try {
            // Create contact record
            $contact = Contact::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'] ?? null,
                'branch_id' => $validated['branch'] ?? null,
                'message' => $validated['message'],
                'status' => 'new',
                'ip_address' => $request->ip(),
                'user_agent' => $request->header('User-Agent'),
            ]);

            return redirect()->back()->with('success', 'Your message has been sent successfully! We will contact you soon.');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to send message. Please try again.');
        }
    }


    public function services()
    {
        $services = Service::all();
        return view('frontend.services', compact('services'));
    }
    public function packages()
    {
        $packages = Package::with('services')
            ->active()
            ->ordered()
            ->get();

        $featuredPackages = Package::with('services')
            ->active()
            ->featured()
            ->ordered()
            ->get();

        return view('frontend.packages', compact('packages', 'featuredPackages'));
    }

    public function storePackage(Request $request)
    {
        $validated = $request->validate([
            'package_id' => 'required|exists:packages,id'
        ]);

        $package = Package::with('services')->find($validated['package_id']);

        // Store package info in session
        session([
            'package' => [
                'type' => 'prebuilt',
                'id' => $package->id,
                'name' => $package->name,
                'price' => $package->final_price ?? $package->price,
                'description' => $package->description,
                'services' => $package->services->map(function ($service) {
                    return [
                        'id' => $service->id,
                        'name' => $service->name,
                        'price' => $service->price,
                        'quantity' => $service->pivot->quantity ?? 1
                    ];
                })->toArray()
            ]
        ]);

        return redirect()->route('request.services.contact')->with('success', 'Package selected successfully!');
    }
}
