<?php

namespace App\Http\Controllers;

use App\Models\CustomCardLayout;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class CustomCardLayoutController extends Controller
{
    // Public: Get all active layouts with cards
    public function index()
    {
        $layouts = CustomCardLayout::active()
            ->ordered()
            ->with('cards')
            ->get();

        return response()->json([
            'message' => 'لیست Layout ها',
            'data' => $layouts
        ]);
    }

    // Public: Get single layout with cards
    public function show($slug)
    {
        $layout = CustomCardLayout::where('slug', $slug)
            ->where('is_active', true)
            ->with('cards')
            ->firstOrFail();

        return response()->json([
            'message' => 'جزئیات Layout',
            'data' => $layout
        ]);
    }

    // Admin: Get all layouts
    public function adminIndex()
    {
        $layouts = CustomCardLayout::ordered()->withCount('cards')->get();

        return response()->json([
            'message' => 'لیست تمام Layout ها',
            'data' => $layouts
        ]);
    }

    // Admin: Create layout
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'show_title' => 'boolean',
            'grid_cols' => 'required|integer|min:3|max:12',
            'grid_rows' => 'required|integer|min:6|max:24',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'اطلاعات نامعتبر است',
                'errors' => $validator->errors()
            ], 422);
        }

        // Generate unique slug
        $slug = Str::slug($request->name);
        $originalSlug = $slug;
        $counter = 1;
        while (CustomCardLayout::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $counter++;
        }

        $layout = CustomCardLayout::create([
            'name' => $request->name,
            'slug' => $slug,
            'show_title' => $request->boolean('show_title', true),
            'grid_cols' => $request->grid_cols,
            'grid_rows' => $request->grid_rows,
            'is_active' => $request->boolean('is_active', true),
            'sort_order' => $request->sort_order ?? 0,
        ]);

        return response()->json([
            'message' => 'Layout با موفقیت ایجاد شد',
            'data' => $layout
        ], 201);
    }

    // Admin: Update layout
    public function update(Request $request, $id)
    {
        $layout = CustomCardLayout::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'show_title' => 'boolean',
            'grid_cols' => 'sometimes|integer|min:3|max:12',
            'grid_rows' => 'sometimes|integer|min:6|max:24',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'اطلاعات نامعتبر است',
                'errors' => $validator->errors()
            ], 422);
        }

        $data = $request->only(['name', 'show_title', 'grid_cols', 'grid_rows', 'is_active', 'sort_order']);

        // Update slug if name changed
        if ($request->has('name') && $request->name !== $layout->name) {
            $slug = Str::slug($request->name);
            $originalSlug = $slug;
            $counter = 1;
            while (CustomCardLayout::where('slug', $slug)->where('id', '!=', $id)->exists()) {
                $slug = $originalSlug . '-' . $counter++;
            }
            $data['slug'] = $slug;
        }

        $layout->update($data);

        return response()->json([
            'message' => 'Layout با موفقیت ویرایش شد',
            'data' => $layout
        ]);
    }

    // Admin: Delete layout
    public function destroy($id)
    {
        $layout = CustomCardLayout::findOrFail($id);
        $layout->delete();

        return response()->json([
            'message' => 'Layout حذف شد'
        ]);
    }

    // Admin: Toggle active
    public function toggleActive($id)
    {
        $layout = CustomCardLayout::findOrFail($id);
        $layout->update(['is_active' => !$layout->is_active]);

        return response()->json([
            'message' => 'وضعیت نمایش تغییر کرد',
            'data' => $layout
        ]);
    }
}
