<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactFormRequest;
use App\Http\Requests\JobApplicationRequest;
use App\GeneralEnquiry;
use App\Service;
use App\Sale;
use App\Portfolio;
use App\Models\Career;
use App\Models\JobApplication;
use App\SeviceEnqury;
use App\SalesEnqury;
use TCG\Voyager\Models\Post;
use TCG\Voyager\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class FrontendController extends Controller
{
    //
    public function index()
    {
        $services = Service::active()->get();
        $sales = Sale::active()->take(6)->get();
        $portfolios = Portfolio::active()->get();
        $recentPosts = Post::where('status', 'PUBLISHED')->orderBy('created_at', 'desc')->take(3)->get();
        return view('frontend.index', compact('services', 'sales', 'portfolios', 'recentPosts'));
    }

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

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

    public function privacy()
    {
        return view('frontend.privacy');
    }
    public function tandc()
    {
        return view('frontend.tandc');
    }
    public function service()
    {
        $services = Service::active()->get();
        return view('frontend.service', compact('services'));
    }

    public function service_detail($slug)
    {
        $service = Service::where('slug', $slug)->where('status', 1)->firstOrFail();
        $allServices = Service::active()->get();
        return view('frontend.service_detail', compact('service', 'allServices'));
    }
    public function sales()
    {
        $sales = Sale::active()->get();
        return view('frontend.sales', compact('sales'));
    }

    public function sales_detail($slug)
    {
        $sale = Sale::where('slug', $slug)->where('status', 1)->firstOrFail();
        $allSales = Sale::active()->get();
        return view('frontend.sales_detail', compact('sale', 'allSales'));
    }
    public function clients()
    {
        $portfolios = Portfolio::active()->get();
        return view('frontend.clients', compact('portfolios'));
    }

    public function blog(Request $request)
    {
        $query = Post::where('status', 'PUBLISHED');

        // Handle category filtering
        if ($request->has('category') && !empty($request->category)) {
            $query->where('category_id', $request->category);
        }

        // Handle search functionality
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $query->where(function($q) use ($searchTerm) {
                $q->where('title', 'LIKE', '%' . $searchTerm . '%')
                  ->orWhere('body', 'LIKE', '%' . $searchTerm . '%')
                  ->orWhere('excerpt', 'LIKE', '%' . $searchTerm . '%');
            });
        }

        // Get paginated posts (6 per page)
        $posts = $query->orderBy('created_at', 'desc')->paginate(6);

        // Get recent posts for sidebar (5 most recent)
        $recentPosts = Post::where('status', 'PUBLISHED')
                          ->orderBy('created_at', 'desc')
                          ->take(5)
                          ->get();

        // Get all categories for sidebar
        $categories = Category::orderBy('name', 'asc')->get();

        return view('frontend.blog', compact('posts', 'recentPosts', 'categories'));
    }

    public function blog_detail($slug)
    {
        $post = Post::where('slug', $slug)->where('status', 'PUBLISHED')->firstOrFail();
        $allPosts = Post::where('status', 'PUBLISHED')->orderBy('created_at', 'desc')->get();
        $categories = Category::orderBy('name', 'asc')->get();
        return view('frontend.blog_detail', compact('post', 'allPosts', 'categories'));
    }

    public function career()
    {
        $careers = Career::active()->orderBy('created_at', 'desc')->get();
        return view('frontend.career', compact('careers'));
    }

    public function career_detail($slug)
    {
        $career = Career::where('slug', $slug)->where('status', 1)->firstOrFail();
        return view('frontend.career_detail', compact('career'));
    }

    public function careerApplicationSubmit(JobApplicationRequest $request)
    {
        try {
            // Get validated data
            $validatedData = $request->validated();

            // Handle file upload
            if ($request->hasFile('resume')) {
                $resumePath = $request->file('resume')->store('resumes', 'public');
                $validatedData['resume'] = $resumePath;
            }

            // Create new job application record
            JobApplication::create($validatedData);

            // Return success response
            return response()->json([
                'success' => true,
                'message' => 'Your application has been submitted successfully! We will review it and get back to you soon.'
            ]);

        } catch (\Exception $exception) {
            // Log the error for debugging
            Log::error('Career application submission error: ' . $exception->getMessage());

            // Return error response
            return response()->json([
                'success' => false,
                'message' => 'Sorry, there was an error submitting your application. Please try again.'
            ], 500);
        }
    }

    public function contactFormSubmit(ContactFormRequest $request)
    {
        try {
            // Get validated data
            $validatedData = $request->validated();

            // Create new enquiry record
            GeneralEnquiry::create($validatedData);

            // Return success response
            return response()->json([
                'success' => true,
                'message' => 'Thank you for your enquiry! We will get back to you soon.'
            ]);

        } catch (\Exception $exception) {
            // Log the error for debugging
            Log::error('Contact form submission error: ' . $exception->getMessage());

            // Return error response
            return response()->json([
                'success' => false,
                'message' => 'Sorry, there was an error submitting your enquiry. Please try again.'
            ], 500);
        }
    }

    public function serviceEnquirySubmit(Request $request)
    {
        try {
            $validated = $request->validate([
                'service_id' => 'required|exists:services,id',
                'name' => 'required|string|max:255',
                'email' => 'required|email|max:255',
                'mobile' => 'required|string|max:55',
                'desc' => 'nullable|string',
            ]);

            SeviceEnqury::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Thank you! Your enquiry has been submitted successfully.'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Please fix the highlighted errors and try again.',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $exception) {
            Log::error('Service enquiry submission error: ' . $exception->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Sorry, there was an error submitting your enquiry. Please try again.'
            ], 500);
        }
    }

    public function salesEnquirySubmit(Request $request)
    {
        try {
            $validated = $request->validate([
                'sales_id' => 'required|exists:sales,id',
                'name' => 'required|string|max:255',
                'email' => 'required|email|max:255',
                'mobile' => 'required|string|max:55',
                'desc' => 'nullable|string',
            ]);

            SalesEnqury::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Thank you! Your sales enquiry has been submitted successfully.'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Please fix the highlighted errors and try again.',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $exception) {
            Log::error('Sales enquiry submission error: ' . $exception->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Sorry, there was an error submitting your enquiry. Please try again.'
            ], 500);
        }
    }

}
