<?php

namespace App\Http\Controllers\Admin;

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

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.tiers.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:tiers',
            'content' => 'nullable',
            'excerpt' => 'nullable',
            '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|url',
            'featured_image' => 'nullable|image|max:2048',
            '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 slug
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }

        // Handle is_featured checkbox
        $validated['is_featured'] = $request->has('is_featured');
        
        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            $path = $request->file('featured_image')->store('tiers/featured', 'public');
            $validated['featured_image'] = $path;
        }
        
        // Handle banner image upload
        if ($request->hasFile('banner_image')) {
            $path = $request->file('banner_image')->store('tiers/banners', 'public');
            $validated['banner_image'] = $path;
        }
        
        // Set author
        $validated['author_id'] = Auth::id();
        $validated['updated_by'] = Auth::id();        $tier = Tier::create($validated);

        return redirect()->route('admin.tiers.show', $tier)
            ->with('success', 'Tier created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Tier $tier)
    {
        return view('admin.tiers.show', compact('tier'));
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Tier $tier)
    {
        $validated = $request->validate([
            'title' => 'required|max:255',
            'slug' => 'nullable|max:255|unique:tiers,slug,' . $tier->id,
            'content' => 'nullable',
            'excerpt' => 'nullable',
            '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|url',
            'featured_image' => 'nullable|image|max:2048',
            '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 slug
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }

        // Handle is_featured checkbox
        $validated['is_featured'] = $request->has('is_featured');
        
        // Handle featured image upload
        if ($request->hasFile('featured_image')) {
            // Delete old image if exists
            if ($tier->featured_image && Storage::disk('public')->exists($tier->featured_image)) {
                Storage::disk('public')->delete($tier->featured_image);
            }
            
            $path = $request->file('featured_image')->store('tiers/featured', 'public');
            $validated['featured_image'] = $path;
        }
        
        // Handle banner image upload
        if ($request->hasFile('banner_image')) {
            // Delete old image if exists
            if ($tier->banner_image && Storage::disk('public')->exists($tier->banner_image)) {
                Storage::disk('public')->delete($tier->banner_image);
            }
            
            $path = $request->file('banner_image')->store('tiers/banners', 'public');
            $validated['banner_image'] = $path;
        }
        
        // Set updated by
        $validated['updated_by'] = Auth::id();        $tier->update($validated);

        return redirect()->route('admin.tiers.show', $tier)
            ->with('success', 'Tier updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Tier $tier)
    {
        // Delete associated images
        if ($tier->featured_image && Storage::disk('public')->exists($tier->featured_image)) {
            Storage::disk('public')->delete($tier->featured_image);
        }
        
        if ($tier->banner_image && Storage::disk('public')->exists($tier->banner_image)) {
            Storage::disk('public')->delete($tier->banner_image);
        }
          $tier->delete();

        return redirect()->route('admin.tiers.index')
            ->with('success', 'Tier deleted successfully.');
    }
}
