<?php

namespace App\Http\Controllers\Agency;

use App\Http\Controllers\Controller;
use App\Http\Requests\Agency\StorePageSectionRequest;
use App\Http\Requests\Agency\UpdatePageSectionRequest;
use App\Models\Agency\AgencyPageSection;
use App\Services\Agency\AgencyPageService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;

class AgencyPageSectionController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        protected AgencyPageService $pageService
    )
    {
    }

    /**
     * Get section data
     */
    public function show(AgencyPageSection $section)
    {
        $this->authorize('view', $section);

        return response()->json([
            'success' => true,
            'section' => $section->load('agencyPage')
        ]);
    }

    /**
     * Add new section
     */
    public function store(StorePageSectionRequest $request)
    {
        $agency = auth()->user()->agency;
        $page = $agency->agencyPage;

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

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

        return response()->json([
            'success' => true,
            'message' => 'Bölüm eklendi',
            'section' => $section,
        ]);
    }

    /**
     * Update section
     */
    public function update(UpdatePageSectionRequest $request, AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $section = $this->pageService->updateSection($section, $request->validated());

        return response()->json([
            'success' => true,
            'message' => 'Bölüm güncellendi',
            'section' => $section,
        ]);
    }

    /**
     * Delete section
     */
    public function destroy(AgencyPageSection $section)
    {
        $this->authorize('delete', $section);

        $this->pageService->deleteSection($section);

        return response()->json([
            'success' => true,
            'message' => 'Bölüm silindi',
        ]);
    }

    /**
     * Reorder sections
     */
    public function reorder(Request $request)
    {
        $request->validate([
            'sections' => 'required|array',
            'sections.*' => 'required|exists:agency_page_sections,id',
        ]);

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

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

        $this->pageService->reorderSections($page, $request->sections);

        return response()->json([
            'success' => true,
            'message' => 'Sıralama güncellendi',
        ]);
    }

    /**
     * Duplicate section
     */
    public function duplicate(AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $newSection = $this->pageService->duplicateSection($section);

        return response()->json([
            'success' => true,
            'message' => 'Bölüm kopyalandı',
            'section' => $newSection,
        ]);
    }

    /**
     * Toggle section visibility
     */
    public function toggle(AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $section = $this->pageService->toggleSection($section);

        return response()->json([
            'success' => true,
            'message' => $section->is_active ? 'Bölüm aktif edildi' : 'Bölüm gizlendi',
            'section' => $section,
        ]);
    }

    /**
     * Upload section image
     */
    public function uploadImage(Request $request, AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $request->validate([
            'image' => 'required|image|max:5120',
            'key' => 'required|string',
        ]);

        try {
            $file = $request->file('image');
            $key = $request->key;

            // Create directory path
            $path = 'agency-pages/' . $section->agencyPage->agency_id . '/sections/' . $section->id;

            // Delete old image if exists
            $oldImage = $section->getConfig($key);
            if ($oldImage && \Storage::exists($oldImage)) {
                \Storage::delete($oldImage);
            }

            // Store new image
            $filename = $key . '_' . time() . '.' . $file->extension();
            $storedPath = $file->storeAs($path, $filename, 'public');

            // Update section config
            $section->setConfigValue($key, $storedPath);
            $section->save();

            return response()->json([
                'success' => true,
                'message' => 'Görsel yüklendi',
                'path' => $storedPath,
                'url' => asset('storage/' . $storedPath),
            ]);
        } catch (\Exception $e) {
            \Log::error('Section image upload error:', ['error' => $e->getMessage()]);

            return response()->json([
                'success' => false,
                'message' => 'Görsel yüklenirken hata oluştu'
            ], 500);
        }
    }

    /**
     * Move section up
     */
    public function moveUp(AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $section->moveUp();

        return response()->json([
            'success' => true,
            'message' => 'Bölüm yukarı taşındı',
        ]);
    }

    /**
     * Move section down
     */
    public function moveDown(AgencyPageSection $section)
    {
        $this->authorize('update', $section);

        $section->moveDown();

        return response()->json([
            'success' => true,
            'message' => 'Bölüm aşağı taşındı',
        ]);
    }
}
