<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SettingsController extends Controller
{
    public function index()
    {
        $settings = [
            'company_name' => Setting::get('company_name', 'Cargo Service'),
            'company_address' => Setting::get('company_address', ''),
            'company_phone' => Setting::get('company_phone', ''),
            'company_email' => Setting::get('company_email', ''),
            'company_logo' => Setting::get('company_logo', ''),
            'company_website' => Setting::get('company_website', ''),
            'office_rawalpindi_title' => Setting::get('office_rawalpindi_title', 'Rawalpindi Office'),
            'office_rawalpindi_status' => Setting::get('office_rawalpindi_status', '1'),
            'office_rawalpindi_address' => Setting::get('office_rawalpindi_address', ''),
            'office_rawalpindi_phone' => Setting::get('office_rawalpindi_phone', ''),
            'office_peshawar_title' => Setting::get('office_peshawar_title', 'Peshawar Office'),
            'office_peshawar_status' => Setting::get('office_peshawar_status', '1'),
            'office_peshawar_address' => Setting::get('office_peshawar_address', ''),
            'office_peshawar_phone' => Setting::get('office_peshawar_phone', ''),
            'office_lahore_title' => Setting::get('office_lahore_title', 'Lahore Office'),
            'office_lahore_status' => Setting::get('office_lahore_status', '1'),
            'office_lahore_address' => Setting::get('office_lahore_address', ''),
            'office_lahore_phone' => Setting::get('office_lahore_phone', ''),
            'currency_symbol' => Setting::get('currency_symbol', 'Rs.'),
            'currency_code' => Setting::get('currency_code', 'PKR'),
            'slider_images' => json_decode(Setting::get('slider_images', '[]'), true) ?? [],
        ];

        return view('settings.index', compact('settings'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'company_name' => 'required|string|max:255',
            'company_address' => 'required|string',
            'company_phone' => 'required|string',
            'company_email' => 'required|email',
            'company_website' => 'nullable|string',
            'office_rawalpindi_title' => 'nullable|string',
            'office_rawalpindi_status' => 'nullable|boolean',
            'office_rawalpindi_address' => 'nullable|string',
            'office_rawalpindi_phone' => 'nullable|string',
            'office_peshawar_title' => 'nullable|string',
            'office_peshawar_status' => 'nullable|boolean',
            'office_peshawar_address' => 'nullable|string',
            'office_peshawar_phone' => 'nullable|string',
            'office_lahore_title' => 'nullable|string',
            'office_lahore_status' => 'nullable|boolean',
            'office_lahore_address' => 'nullable|string',
            'office_lahore_phone' => 'nullable|string',
            'currency_symbol' => 'required|string|max:10',
            'currency_code' => 'required|string|max:10',
            'slider_images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        // Remove slider_images from validated array as we handle it separately
        unset($validated['slider_images']);

        // Handle checkboxes for office status (if unchecked, they won't be in request, so set to 0)
        $offices = ['office_rawalpindi_status', 'office_peshawar_status', 'office_lahore_status'];
        foreach ($offices as $office) {
            if (!isset($validated[$office])) {
                $validated[$office] = '0';
            }
        }

        foreach ($validated as $key => $value) {
            Setting::set($key, $value);
        }

        // Handle logo upload
        if ($request->hasFile('company_logo')) {
            $file = $request->file('company_logo');
            $filename = 'logo_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads'), $filename);
            Setting::set('company_logo', $filename);
        }

        // Handle Slider Images
        if ($request->hasFile('slider_images')) {
            $existingImages = json_decode(Setting::get('slider_images', '[]'), true) ?? [];
            $newImages = [];
            
            // Ensure directory exists
            if (!file_exists(public_path('uploads/sliders'))) {
                mkdir(public_path('uploads/sliders'), 0755, true);
            }
            
            foreach ($request->file('slider_images') as $image) {
                $filename = 'slider_' . uniqid() . '.' . $image->getClientOriginalExtension();
                $image->move(public_path('uploads/sliders'), $filename);
                $newImages[] = $filename;
            }
            
            $allImages = array_merge($existingImages, $newImages);
            Setting::set('slider_images', json_encode($allImages));
        }

        // Clear all settings cache
        Cache::forget('all_settings');

        return redirect()->route('settings.index')->with('success', 'Settings updated successfully!');
    }

    public function deleteSliderImage(Request $request)
    {
        $request->validate(['image' => 'required|string']);
        
        $images = json_decode(Setting::get('slider_images', '[]'), true) ?? [];
        $imageToDelete = $request->image;
        
        if (($key = array_search($imageToDelete, $images)) !== false) {
            unset($images[$key]);
            // Delete file
            if (file_exists(public_path('uploads/sliders/' . $imageToDelete))) {
                unlink(public_path('uploads/sliders/' . $imageToDelete));
            }
            Setting::set('slider_images', json_encode(array_values($images)));
            Cache::forget('all_settings');
        }
        
        return back()->with('success', 'Slider image deleted successfully!');
    }
}
