<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Benefit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BenefitController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $benefits = Benefit::orderBy('sort_order')
                          ->orderBy('title')
                          ->paginate(10);
        return view('admin.benefits.index', compact('benefits'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.benefits.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|max:255',
            'slug' => 'nullable|max:255|unique:benefits',
            'content' => 'nullable',
            'excerpt' => 'nullable',
            'custom_link' => 'nullable|url|max:255',
            'status' => 'required|in:draft,published,archived',
            'sort_order' => 'nullable|integer',
            'is_featured' => 'boolean',
            'published_at' => 'nullable|date',
            'meta_title' => 'nullable|max:255',
            'meta_description' => 'nullable',
            'meta_keywords' => 'nullable',
            'meta_robots' => 'nullable|max:255',
            'canonical_url' => 'nullable|max:255',
            'schema_markup' => 'nullable',
            'featured_image' => 'nullable|image|max:2048', // 2MB max
            'featured_image_alt' => 'nullable|max:255',
            'featured_image_caption' => 'nullable|max:255',
            'banner_image' => 'nullable|image|max:2048',
            'banner_image_alt' => 'nullable|max:255',
        ]);
        
        // Handle image uploads
        if ($request->hasFile('featured_image')) {
            $validated['featured_image'] = $request->file('featured_image')->store('benefits/featured', 'public');
        }
        
        if ($request->hasFile('banner_image')) {
            $validated['banner_image'] = $request->file('banner_image')->store('benefits/banners', 'public');
        }
        
        // Set the author
        $validated['author_id'] = Auth::id();
        $validated['updated_by'] = Auth::id();
        
        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }
        
        Benefit::create($validated);
        
        return redirect()->route('admin.benefits.index')
            ->with('success', 'Benefit created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Benefit $benefit)
    {
        return view('admin.benefits.show', compact('benefit'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Benefit $benefit)
    {
        return view('admin.benefits.edit', compact('benefit'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Benefit $benefit)
    {
        $validated = $request->validate([
            'title' => 'required|max:255',
            'slug' => 'nullable|max:255|unique:benefits,slug,'.$benefit->id,
            'content' => 'nullable',
            'excerpt' => 'nullable',
            'custom_link' => 'nullable|url|max:255',
            'status' => 'required|in:draft,published,archived',
            'sort_order' => 'nullable|integer',
            'is_featured' => 'boolean',
            'published_at' => 'nullable|date',
            'meta_title' => 'nullable|max:255',
            'meta_description' => 'nullable',
            'meta_keywords' => 'nullable',
            'meta_robots' => 'nullable|max:255',
            'canonical_url' => 'nullable|max:255',
            'schema_markup' => 'nullable',
            'featured_image' => 'nullable|image|max:2048', // 2MB max
            'featured_image_alt' => 'nullable|max:255',
            'featured_image_caption' => 'nullable|max:255',
            'banner_image' => 'nullable|image|max:2048',
            'banner_image_alt' => 'nullable|max:255',
        ]);
        
        // Handle image uploads
        if ($request->hasFile('featured_image')) {
            // Delete old image if exists
            if ($benefit->featured_image) {
                Storage::disk('public')->delete($benefit->featured_image);
            }
            $validated['featured_image'] = $request->file('featured_image')->store('benefits/featured', 'public');
        }
        
        if ($request->hasFile('banner_image')) {
            // Delete old image if exists
            if ($benefit->banner_image) {
                Storage::disk('public')->delete($benefit->banner_image);
            }
            $validated['banner_image'] = $request->file('banner_image')->store('benefits/banners', 'public');
        }
        
        // Set the updater
        $validated['updated_by'] = Auth::id();
        
        // Generate slug if not provided
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }
        
        $benefit->update($validated);
        
        return redirect()->route('admin.benefits.index')
            ->with('success', 'Benefit updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Benefit $benefit)
    {
        // Delete associated images
        if ($benefit->featured_image) {
            Storage::disk('public')->delete($benefit->featured_image);
        }
        
        if ($benefit->banner_image) {
            Storage::disk('public')->delete($benefit->banner_image);
        }
        
        $benefit->delete();
        
        return redirect()->route('admin.benefits.index')
            ->with('success', 'Benefit deleted successfully.');
    }
}
