<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\VipCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;

class AdminVipCardController extends Controller
{
    /**
     * List all VIP cards
     */
    public function index()
    {
        $cards = VipCard::withCount('orders')
            ->orderBy('sort_order')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('admin.vip-cards.index', compact('cards'))
            ->with('title', 'VIP Cards');
    }

    /**
     * Show create form
     */
    public function create()
    {
        return view('admin.vip-cards.create')
            ->with('title', 'Add New VIP Card');
    }

    /**
     * Store new VIP card
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'              => 'required|string|max:255',
            'description'       => 'nullable|string',
            'short_description' => 'nullable|string|max:500',
            'price'             => 'required|numeric|min:0',
            'duration_days'     => 'required|integer|min:1',
            'benefits'          => 'nullable|string',
            'card_image'        => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'color'             => 'nullable|string|max:50',
            'sort_order'        => 'nullable|integer|min:0',
            'featured'              => 'nullable|boolean',
            'status'                => 'required|in:active,inactive',
            'giveaway_multiplier'   => 'nullable|numeric|min:1',
            'car_discount'          => 'nullable|numeric|min:0|max:100',
            'investment_bonus'      => 'nullable|numeric|min:0|max:100',
            'priority_support'      => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $request->only([
            'name', 'description', 'short_description', 'price',
            'duration_days', 'color', 'sort_order', 'status',
            'giveaway_multiplier', 'car_discount', 'investment_bonus',
        ]);

        $data['priority_support'] = $request->has('priority_support') ? 1 : 0;

        // Parse benefits (one per line)
        if ($request->benefits) {
            $data['benefits'] = array_values(array_filter(
                array_map('trim', explode("\n", $request->benefits))
            ));
        }

        $data['featured'] = $request->has('featured') ? 1 : 0;

        // Handle card image upload
        if ($request->hasFile('card_image')) {
            $dir = base_path('dash/vip-cards');
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            $filename = uniqid() . '.' . $request->file('card_image')->getClientOriginalExtension();
            $request->file('card_image')->move($dir, $filename);
            $data['card_image'] = 'vip-cards/' . $filename;
        }

        VipCard::create($data);

        return redirect()->route('admin.vip-cards.index')
            ->with('success', 'VIP Card created successfully.');
    }

    /**
     * Show edit form
     */
    public function edit(VipCard $vipCard)
    {
        return view('admin.vip-cards.edit', compact('vipCard'))
            ->with('title', 'Edit VIP Card - ' . $vipCard->name);
    }

    /**
     * Update VIP card
     */
    public function update(Request $request, VipCard $vipCard)
    {
        $validator = Validator::make($request->all(), [
            'name'              => 'required|string|max:255',
            'description'       => 'nullable|string',
            'short_description' => 'nullable|string|max:500',
            'price'             => 'required|numeric|min:0',
            'duration_days'     => 'required|integer|min:1',
            'benefits'          => 'nullable|string',
            'card_image'        => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'color'             => 'nullable|string|max:50',
            'sort_order'        => 'nullable|integer|min:0',
            'featured'              => 'nullable|boolean',
            'status'                => 'required|in:active,inactive',
            'giveaway_multiplier'   => 'nullable|numeric|min:1',
            'car_discount'          => 'nullable|numeric|min:0|max:100',
            'investment_bonus'      => 'nullable|numeric|min:0|max:100',
            'priority_support'      => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $request->only([
            'name', 'description', 'short_description', 'price',
            'duration_days', 'color', 'sort_order', 'status',
            'giveaway_multiplier', 'car_discount', 'investment_bonus',
        ]);

        $data['priority_support'] = $request->has('priority_support') ? 1 : 0;

        // Parse benefits
        if ($request->benefits) {
            $data['benefits'] = array_values(array_filter(
                array_map('trim', explode("\n", $request->benefits))
            ));
        } else {
            $data['benefits'] = [];
        }

        $data['featured'] = $request->has('featured') ? 1 : 0;

        // Handle card image upload
        if ($request->hasFile('card_image')) {
            // Delete old image
            if ($vipCard->card_image && File::exists(base_path('dash/' . $vipCard->card_image))) {
                File::delete(base_path('dash/' . $vipCard->card_image));
            }
            $dir = base_path('dash/vip-cards');
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            $filename = uniqid() . '.' . $request->file('card_image')->getClientOriginalExtension();
            $request->file('card_image')->move($dir, $filename);
            $data['card_image'] = 'vip-cards/' . $filename;
        }

        $vipCard->update($data);

        return redirect()->route('admin.vip-cards.index')
            ->with('success', 'VIP Card updated successfully.');
    }

    /**
     * Toggle active/inactive status
     */
    public function toggleStatus(VipCard $vipCard)
    {
        $vipCard->update([
            'status' => $vipCard->status === 'active' ? 'inactive' : 'active',
        ]);

        return redirect()->route('admin.vip-cards.index')
            ->with('success', "VIP Card {$vipCard->name} is now {$vipCard->status}.");
    }

    /**
     * Delete VIP card (soft delete)
     */
    public function destroy(VipCard $vipCard)
    {
        $vipCard->delete();

        return redirect()->route('admin.vip-cards.index')
            ->with('success', 'VIP Card deleted successfully.');
    }
}
