<?php

namespace App\Http\Controllers\Admin;

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

class StoryController extends Controller
{
    /**
     * Get all stories
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = Story::query();

            if ($request->has('is_active')) {
                $query->where('is_active', $request->is_active === 'true');
            }

            $stories = $query->with('brands')->orderBy('order')->orderBy('created_at', 'desc')->get();

            return response()->json([
                'data' => $stories
            ]);
        } catch (\Exception $e) {
            Log::error('Stories index error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Get story by ID
     */
    public function show(int $id): JsonResponse
    {
        try {
            $story = Story::with('brands')->findOrFail($id);
            return response()->json(['data' => $story]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Create new story
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'image' => 'required|string',
                'title' => 'required|string|max:255',
                'description' => 'required|string',
                'button_text' => 'nullable|string|max:255',
                'button_link' => 'nullable|string|max:500',
                'order' => 'nullable|integer',
                'is_active' => 'nullable|boolean',
                'brand_ids' => 'nullable|array',
                'brand_ids.*' => 'exists:brands,id',
            ]);

            $story = Story::create($validated);

            // Sync brands
            if ($request->has('brand_ids')) {
                $story->brands()->sync($request->brand_ids);
            }

            return response()->json([
                'data' => $story->load('brands'),
                'message' => 'Story created successfully'
            ], 201);
        } catch (\Exception $e) {
            Log::error('Story create error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Update story
     */
    public function update(Request $request, int $id): JsonResponse
    {
        try {
            $story = Story::findOrFail($id);

            $validated = $request->validate([
                'image' => 'sometimes|required|string',
                'title' => 'sometimes|required|string|max:255',
                'description' => 'sometimes|required|string',
                'button_text' => 'nullable|string|max:255',
                'button_link' => 'nullable|string|max:500',
                'order' => 'nullable|integer',
                'is_active' => 'nullable|boolean',
                'brand_ids' => 'nullable|array',
                'brand_ids.*' => 'exists:brands,id',
            ]);

            $story->update($validated);

            // Sync brands
            if ($request->has('brand_ids')) {
                $story->brands()->sync($request->brand_ids);
            }

            return response()->json([
                'data' => $story->load('brands'),
                'message' => 'Story updated successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Story update error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Delete story
     */
    public function destroy(int $id): JsonResponse
    {
        try {
            $story = Story::findOrFail($id);
            $story->delete();

            return response()->json([
                'message' => 'Story deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
