<?php

namespace App\Http\Controllers;

use App\Models\CompanyInfo;
use App\Models\CompanyStat;
use App\Models\CompanyValue;
use App\Models\ContactInfo;
use App\Models\Faq;
use App\Models\ServiceItem;
use App\Models\SiteSetting;
use App\Models\Slider;
use App\Models\TimelineEvent;
use App\Models\Vehicle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class PublicController extends Controller
{
    public function welcome()
    {
        return view('welcome');
    }

    public function dashboard()
    {
        return view('dashboard');
    }

    public function termsRedirect()
    {
        return redirect()->route('terms');
    }

    public function privacyRedirect()
    {
        return redirect()->route('privacy');
    }

    public function index()
    {
        $sliders = Schema::hasTable('sliders')
            ? Slider::where('is_active', true)->orderBy('order')->get()
            : collect();

        $featuredVehicles = Schema::hasTable('vehicles')
            ? Vehicle::where('status', 'AVAILABLE')
                ->with(['images', 'pricing'])
                ->latest()
                ->take(6)
                ->get()
            : collect();

        $companyInfo = $this->getCompanyInfo();
        $services = Schema::hasTable('service_items') ? ServiceItem::where('is_active', true)->orderBy('order')->get() : collect();
        $stats = Schema::hasTable('company_stats') ? CompanyStat::orderBy('order')->get() : collect();
        $values = Schema::hasTable('company_values') ? CompanyValue::orderBy('order')->get() : collect();
        $timeline = Schema::hasTable('timeline_events') ? TimelineEvent::orderBy('order')->get() : collect();
        $contactInfo = $this->getContactInfo();

        return view('public.home', compact(
            'sliders',
            'featuredVehicles',
            'companyInfo',
            'services',
            'stats',
            'values',
            'timeline',
            'contactInfo'
        ));
    }

    public function about()
    {
        return view('public.about', [
            'companyInfo' => $this->getCompanyInfo(),
            'values' => Schema::hasTable('company_values') ? CompanyValue::orderBy('order')->get() : collect(),
            'timeline' => Schema::hasTable('timeline_events') ? TimelineEvent::orderBy('order')->get() : collect(),
        ]);
    }

    public function contact()
    {
        return view('public.contact', ['contactInfo' => $this->getContactInfo()]);
    }

    public function contactSubmit(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string|max:5000',
        ]);

        \App\Models\ContactMessage::create($validated);

        return redirect()->back()->with('success', 'تم استلام رسالتك بنجاح. سنتواصل معك قريباً.');
    }

    public function consultation()
    {
        return view('public.consultation');
    }

    public function consultationSubmit(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'topic' => 'required|string|max:255',
            'details' => 'nullable|string|max:5000',
        ]);

        // Store as ContactMessage with specific subject prefix
        \App\Models\ContactMessage::create([
            'name' => $validated['name'],
            'email' => 'no-email@consultation.com', // Placeholder or add email field
            'phone' => $validated['phone'],
            'subject' => 'طلب استشارة: '.$validated['topic'],
            'message' => $validated['details'] ?? 'No details provided.',
        ]);

        return redirect()->back()->with('success', 'تم استلام طلب الاستشارة بنجاح. سنتواصل معك قريباً.');
    }

    public function parts()
    {
        return view('public.parts', ['contactInfo' => $this->getContactInfo()]);
    }

    public function warranty()
    {
        return view('public.warranty', ['contactInfo' => $this->getContactInfo()]);
    }

    public function faq()
    {
        $faqs = Schema::hasTable('faqs')
            ? Faq::where('is_active', true)->orderBy('order')->get()->groupBy('category')
            : collect();

        return view('public.faq', ['contactInfo' => $this->getContactInfo(), 'faqs' => $faqs]);
    }

    public function support()
    {
        return view('public.support', ['contactInfo' => $this->getContactInfo()]);
    }

    public function terms()
    {
        return view('public.terms');
    }

    public function privacy()
    {
        return view('public.privacy');
    }

    public function tataMotors()
    {
        return view('public.tata-motors');
    }

    private function getCompanyInfo()
    {
        if (Schema::hasTable('company_infos')) {
            $record = CompanyInfo::first();
            if ($record) {
                return $record;
            }
        }

        return (object) [
            'name' => 'شركة الحمد لاستيراد السيارات',
            'description' => 'الموزع المعتمد لسيارات تاتا في مدن القناة',
            'mission' => 'نقدم منتجات وخدمات عالية الجودة',
            'vision' => 'نسعى دائماً للابتكار',
        ];
    }

    private function getContactInfo()
    {
        $info = Schema::hasTable('contact_info') ? ContactInfo::first() : null;
        if (! $info) {
            // Fallback to SiteSettings if ContactInfo missing (or legacy structure)
            $settings = Schema::hasTable('site_settings') ? SiteSetting::first() : null;

            return (object) [
                'primary_phone' => $settings->contact_phone ?? '+201555767729',
                'primary_email' => $settings->contact_email ?? 'info@elhamdimport.online',
                'address' => $settings->contact_address ?? 'بورسعيد، مصر',
                'map_url' => 'https://maps.google.com/?q=30.0131,31.2089',
                'working_hours' => [],
            ];
        }

        return $info;
    }

    public function serviceBooking()
    {
        $serviceTypes = Schema::hasTable('service_types')
            ? \App\Models\ServiceType::where('is_active', true)->get()
            : collect();
        $vehicles = Schema::hasTable('vehicles')
            ? Vehicle::where('status', 'AVAILABLE')->with(['images', 'pricing'])->get()
            : collect();

        return view('public.service-booking', compact('serviceTypes', 'vehicles'));
    }

    public function testDrive()
    {
        $vehicles = Schema::hasTable('vehicles')
            ? Vehicle::where('status', 'AVAILABLE')->with(['images', 'pricing'])->get()
            : collect();

        return view('public.test-drive', compact('vehicles'));
    }
}
