<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use App\Http\Requests\Agency\UpdateAgencyPageRequest;
use App\Http\Requests\Agency\UpdateThemeSettingsRequest;
use App\Models\Agency\Agency;
use App\Models\Agency\AgencyPage;
use App\Models\Agency\AgencyTheme;
use App\Services\Agency\AgencyPageService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;

class AgencyPageController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        protected AgencyPageService $pageService
    )
    {
    }

    /**
     * Display agency page editor
     */
    public function index()
    {
        $agency = auth()->user()->agency;

        if (!$agency) {
            abort(403, 'You must belong to an agency');
        }

        $page = $this->pageService->getOrCreatePage($agency);
        $themes = AgencyTheme::ordered()->get();

        return view('agency.page.editor', compact('page', 'themes')); // editor view'a yönlendir
    }

    /**
     * Get page data
     */
    public function show()
    {
        $agency = auth()->user()->agency;
        $page = $this->pageService->getOrCreatePage($agency);

        return response()->json([
            'page' => $page->load(['theme', 'sections' => fn($q) => $q->ordered()]),
            'themes' => AgencyTheme::ordered()->get(),
            'available_sections' => $this->pageService->getAvailableSectionTypes($page),
        ]);
    }

    /**
     * Update page settings
     */
    public function update(UpdateAgencyPageRequest $request)
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $page = $this->pageService->updatePage($page, $request->validated());

        return response()->json([
            'success' => true,
            'message' => 'Sayfa ayarları güncellendi',
            'page' => $page->load('theme'),
        ]);
    }

    /**
     * Change theme
     */
    public function changeTheme(Request $request)
    {
        $request->validate([
            'theme_id' => 'required|exists:agency_themes,id',
        ]);

        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $page = $this->pageService->changeTheme($page, $request->theme_id);

        return response()->json([
            'success' => true,
            'message' => 'Tema değiştirildi',
            'page' => $page->load('theme'),
        ]);
    }

    /**
     * Update theme settings
     */
    public function updateThemeSettings(Request $request)
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        // Dot notation'ı nested array'e çevir
        $data = [];
        foreach ($request->all() as $key => $value) {
            if (strpos($key, '.') !== false) {
                $parts = explode('.', $key, 2); // Sadece ilk noktadan böl
                if (!isset($data[$parts[0]])) {
                    $data[$parts[0]] = [];
                }
                $data[$parts[0]][$parts[1]] = $value;
            } else {
                $data[$key] = $value;
            }
        }

        \Log::info('Converted data:', $data);

        // Şimdi kaydet
        $overrides = $page->theme_overrides ?? [];

        foreach ($data as $category => $values) {
            if (is_array($values)) {
                foreach ($values as $key => $value) {
                    if (is_null($value)) {
                        // Null ise sil
                        if (isset($overrides[$category][$key])) {
                            unset($overrides[$category][$key]);
                        }
                        if (isset($overrides[$category]) && empty($overrides[$category])) {
                            unset($overrides[$category]);
                        }
                    } else {
                        // Değer varsa kaydet
                        if (!isset($overrides[$category])) {
                            $overrides[$category] = [];
                        }
                        $overrides[$category][$key] = $value;
                    }
                }
            }
        }

        \Log::info('Final overrides:', $overrides);

        $page->theme_overrides = $overrides;
        $page->save();

        return response()->json([
            'success' => true,
            'message' => 'Tema ayarları güncellendi',
            'saved_data' => $page->fresh()->theme_overrides
        ]);
    }

    /**
     * Upload hero image
     */
    public function uploadHeroImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|max:5120',
        ]);

        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $path = $this->pageService->uploadHeroImage($page, $request->file('image'));

        return response()->json([
            'success' => true,
            'message' => 'Hero görseli yüklendi',
            'path' => $path,
            'url' => asset('storage/' . $path),
        ]);
    }

    /**
     * Publish page
     */
    public function publish()
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $page = $this->pageService->publish($page);

        return response()->json([
            'success' => true,
            'message' => 'Sayfa yayınlandı',
            'page' => $page,
        ]);
    }

    /**
     * Unpublish page
     */
    public function unpublish()
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $page = $this->pageService->unpublish($page);

        return response()->json([
            'success' => true,
            'message' => 'Sayfa yayından kaldırıldı',
            'page' => $page,
        ]);
    }

    /**
     * Preview page
     */
    public function preview()
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $previewData = $this->pageService->getPreviewData($page);

        return view('agency.page.preview', $previewData);
    }

    /**
     * Get revisions
     */
    public function revisions()
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $revisions = $page->revisions()
            ->with('creator')
            ->latest()
            ->paginate(20);

        return response()->json($revisions);
    }

    /**
     * Restore revision
     */
    public function restoreRevision(Request $request)
    {
        $request->validate([
            'revision_id' => 'required|exists:agency_page_revisions,id',
        ]);

        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

        if (!$page) {
            abort(404);
        }

        $page = $this->pageService->restoreRevision($page, $request->revision_id);

        return response()->json([
            'success' => true,
            'message' => 'Sayfa geri yüklendi',
            'page' => $page->load(['theme', 'sections']),
        ]);
    }
}
