<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Page;
use App\Models\Country;
use App\Models\Locale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PageController extends Controller
{
    /**
     * Display a listing of pages
     */
    public function index(Request $request)
    {
        $query = Page::with(['translations.locale']);

        // Get current country filter from session
        $currentCountry = current_filtered_country();
        $availableLocales = collect();
        
        if ($currentCountry) {
            $availableLocales = Locale::where('country_id', $currentCountry->id)
                                    ->active()
                                    ->ordered()
                                    ->get();
        }

        // Locale filter
        if ($request->filled('locale_id')) {
            $query->whereHas('translations', function ($q) use ($request) {
                $q->where('locale_id', $request->locale_id);
            });
        }

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->whereHas('translations', function ($tq) use ($search) {
                    $tq->where('title', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%");
                });
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $pages = $query->latest()->paginate(15)->withQueryString();

        return view('admin.pages.index', compact(
            'pages',
            'availableLocales',
            'currentCountry'
        ));
    }

    /**
     * Store a newly created page
     */
    public function store(Request $request)
    {
        $request->validate([
            'translations' => 'required|array',
            'status' => 'required|in:draft,published',
        ]);

        // Check if at least one translation exists
        $hasTranslation = false;
        foreach ($request->translations as $translation) {
            if (!empty($translation['title'])) {
                $hasTranslation = true;
                break;
            }
        }

        if (!$hasTranslation) {
            return back()->withErrors([
                'translations' => admin_trans('at_least_one_page_title_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            $page = Page::create([
                'status' => $request->status,
            ]);

            // Store translations
            foreach ($request->translations as $localeId => $translation) {
                if (!empty($translation['title'])) {
                    $page->translations()->create([
                        'locale_id' => $localeId,
                        'title' => $translation['title'],
                        'description' => $translation['description'] ?? null,
                    ]);
                }
            }

            DB::commit();
            flash_success(admin_trans('page_created_successfully'));
            return redirect()->route('admin.pages.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_creating_page'));
            return back()->withInput();
        }
    }

    /**
     * Show the form for editing the specified page
     */
    public function edit(Page $page)
    {
        try {
            $page->load(['translations.locale']);

            $data = [
                'id' => $page->id,
                'status' => $page->status,
                'translations' => $page->translations->toArray(),
            ];

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_loading_page')
            ], 500);
        }
    }

    /**
     * Update the specified page
     */
    public function update(Request $request, Page $page)
    {
        $request->validate([
            'translations' => 'required|array',
            'status' => 'required|in:draft,published',
        ]);

        // Check if at least one translation exists
        $hasTranslation = false;
        foreach ($request->translations as $translation) {
            if (!empty($translation['title'])) {
                $hasTranslation = true;
                break;
            }
        }

        if (!$hasTranslation) {
            return back()->withErrors([
                'translations' => admin_trans('at_least_one_page_title_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            $page->update([
                'status' => $request->status,
            ]);

            // Clear existing translations
            $page->translations()->delete();

            // Store translations
            foreach ($request->translations as $localeId => $translation) {
                if (!empty($translation['title'])) {
                    $page->translations()->create([
                        'locale_id' => $localeId,
                        'title' => $translation['title'],
                        'description' => $translation['description'] ?? null,
                    ]);
                }
            }

            DB::commit();
            flash_success(admin_trans('page_updated_successfully'));
            return redirect()->route('admin.pages.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_updating_page'));
            return back()->withInput();
        }
    }

    /**
     * Remove the specified page
     */
    public function destroy(Page $page)
    {
        try {
            $page->delete();
            flash_success(admin_trans('page_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_page'));
        }

        return redirect()->route('admin.pages.index');
    }

    /**
     * Toggle page status
     */
    public function toggleStatus(Page $page)
    {
        try {
            $newStatus = $page->status === 'published' ? 'draft' : 'published';
            $page->update(['status' => $newStatus]);
            
            flash_success(admin_trans('page_status_updated'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_status'));
        }

        return back();
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:delete,publish,draft',
            'selected' => 'required|array',
            'selected.*' => 'exists:pages,id',
        ]);

        $pages = Page::whereIn('id', $request->selected);
        $count = count($request->selected);

        try {
            switch ($request->action) {
                case 'delete':
                    $pages->delete();
                    break;

                case 'publish':
                    $pages->update(['status' => 'published']);
                    break;

                case 'draft':
                    $pages->update(['status' => 'draft']);
                    break;
            }

            return response()->json([
                'success' => true,
                'message' => "$count " . admin_trans('pages') . " {$request->action}d " . admin_trans('successfully')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_bulk_action')
            ]);
        }
    }
}