<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContactInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ContactController extends Controller
{
    public function index()
    {
        $contactSections = ContactInfo::all();
        return view('admin.contact.index', compact('contactSections'));
    }

    public function edit()
    {
        $heroSection = ContactInfo::where('section_key', 'hero')->first();
        $officesSection = ContactInfo::where('section_key', 'offices')->first();
        $quickContactSection = ContactInfo::where('section_key', 'quick_contact')->first();

        return view('admin.contact.edit', compact('heroSection', 'officesSection', 'quickContactSection'));
    }

    public function update(Request $request)
    {
        try {
            $request->validate([
                'hero_title' => 'required|string|max:255',
                'hero_content' => 'required|string|max:1000',
                'offices_title' => 'required|string|max:255',
                'offices_content' => 'required|string|max:1000',
                'quick_contact_title' => 'required|string|max:255',
                'quick_contact_content' => 'required|string|max:1000',
            ]);

            // Update Hero Section
            ContactInfo::updateOrCreate(
                ['section_key' => 'hero'],
                [
                    'title' => $request->input('hero_title'),
                    'content' => $request->input('hero_content'),
                    'is_active' => true
                ]
            );

            // Update Offices Section
            ContactInfo::updateOrCreate(
                ['section_key' => 'offices'],
                [
                    'title' => $request->input('offices_title'),
                    'content' => $request->input('offices_content'),
                    'is_active' => true
                ]
            );

            // Update Quick Contact Section
            ContactInfo::updateOrCreate(
                ['section_key' => 'quick_contact'],
                [
                    'title' => $request->input('quick_contact_title'),
                    'content' => $request->input('quick_contact_content'),
                    'is_active' => true
                ]
            );

            return redirect()->route('admin.contact.edit')
                ->with('success', 'Contact page updated successfully!');
        } catch (\Exception $e) {
            Log::error('Error updating contact page: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while updating the contact page.');
        }
    }

    public function addOffice(Request $request)
    {
        try {
            $request->validate([
                'city' => 'required|string|max:255',
                'country' => 'required|string|max:255',
                'address' => 'required|string|max:500',
                'phone' => 'required|string|max:50',
                'email' => 'required|email|max:255',
                'hours' => 'required|string|max:255',
                'description' => 'required|string|max:500',
            ]);

            $officesSection = ContactInfo::where('section_key', 'offices')->first();

            if (!$officesSection) {
                return response()->json([
                    'success' => false,
                    'message' => 'Offices section not found.'
                ], 404);
            }

            // Get existing offices
            $data = $officesSection->getAttribute('data') ?? [];
            $existingOffices = isset($data['offices']) ? $data['offices'] : [];

            // Add new office
            $newOffice = [
                'city' => $request->input('city'),
                'country' => $request->input('country'),
                'address' => $request->input('address'),
                'phone' => $request->input('phone'),
                'email' => $request->input('email'),
                'hours' => $request->input('hours'),
                'description' => $request->input('description'),
            ];

            $existingOffices[] = $newOffice;

            // Update section with new offices
            $data['offices'] = $existingOffices;
            $officesSection->update(['data' => $data]);

            return response()->json([
                'success' => true,
                'message' => 'Office added successfully!',
                'office' => $newOffice
            ]);
        } catch (\Exception $e) {
            Log::error('Error adding office: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while adding the office.'
            ], 500);
        }
    }

    public function removeOffice(Request $request)
    {
        try {
            $request->validate([
                'index' => 'required|integer|min:0'
            ]);

            $officesSection = ContactInfo::where('section_key', 'offices')->first();

            if (!$officesSection) {
                return response()->json([
                    'success' => false,
                    'message' => 'Offices section not found.'
                ], 404);
            }

            $data = $officesSection->getAttribute('data') ?? [];
            $existingOffices = isset($data['offices']) ? $data['offices'] : [];

            $index = $request->input('index');

            if (!isset($existingOffices[$index])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Office not found.'
                ], 404);
            }

            // Remove office
            array_splice($existingOffices, $index, 1);

            // Update section
            $data['offices'] = $existingOffices;
            $officesSection->update(['data' => $data]);

            return response()->json([
                'success' => true,
                'message' => 'Office removed successfully!'
            ]);
        } catch (\Exception $e) {
            Log::error('Error removing office: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while removing the office.'
            ], 500);
        }
    }
}
