<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Setting;
use App\Models\Rate;
use Illuminate\Http\Request;

class FrontendController extends Controller
{
    private function getSettings()
    {
        $sliderImages = json_decode(Setting::get('slider_images', '[]'), true) ?? [];
        
        // Use defaults if no images uploaded
        if (empty($sliderImages)) {
            $sliderImages = [
                'https://images.unsplash.com/photo-1586155638764-bf045442f6f3?auto=format&fit=crop&q=80&w=1600', 
                'https://images.unsplash.com/photo-1494412574643-35d324698420?auto=format&fit=crop&q=80&w=1600', 
                'https://images.unsplash.com/photo-1601584115197-04ecc0da31d7?auto=format&fit=crop&q=80&w=1600'
            ];
        } else {
            // Map to relative URLs to avoid host mismatches
             $sliderImages = array_map(function($img) {
                 return '/uploads/sliders/' . $img;
             }, $sliderImages);
        }

        return (object) [
            'company_name' => Setting::get('company_name', 'Cargo Service'),
            'company_logo' => Setting::get('company_logo', ''),
            'company_phone' => Setting::get('company_phone', '+92 300 1234567'),
            'company_email' => Setting::get('company_email', 'info@cargoservice.com'),
            'company_address' => Setting::get('company_address', '123 Cargo Street, Logistics City, Pakistan'),
            'currency_symbol' => Setting::get('currency_symbol', 'Rs.'),
            'slider_images' => $sliderImages,
        ];
    }

    public function index()
    {
        $settings = $this->getSettings();
        $rates = Rate::whereNull('customer_id')->where('is_active', true)->get();
        return view('frontend.home', compact('settings', 'rates'));
    }

    public function track(Request $request)
    {
        $booking = null;
        $cntr_no = $request->input('cntr_no');
        
        if ($cntr_no) {
            $booking = Booking::where('cntr_no', $cntr_no)
                ->with(['customer', 'tracking' => function($query) {
                    $query->latest('status_date');
                }])
                ->first();
        }

        $settings = $this->getSettings();
        return view('frontend.track', compact('booking', 'cntr_no', 'settings'));
    }

    public function about()
    {
        $settings = $this->getSettings();
        return view('frontend.about', compact('settings'));
    }
}
