<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PromotionPackage;
use Illuminate\Http\Request;

class PromotionPackageController extends Controller
{
    public function index()
    {
        $packages = PromotionPackage::latest()->get();
        return view('admin.promotions.packages.index', compact('packages'));
    }

    public function create()
    {
        return view('admin.promotions.packages.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'price_usd' => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'page_position' => 'required|integer|in:1,2',
            'max_products' => 'required|integer|min:1',
            'priority_level' => 'required|integer|min:1|max:10',
            'badge_text' => 'required|string|max:50',
            'badge_color' => 'required|string|max:7',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        PromotionPackage::create($validated);

        return redirect()->route('admin.promotions.packages.index')
                        ->with('success', 'Promotion package created successfully!');
    }

    public function edit(PromotionPackage $package)
    {
        return view('admin.promotions.packages.edit', compact('package'));
    }

    public function update(Request $request, PromotionPackage $package)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'price_usd' => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'page_position' => 'required|integer|in:1,2',
            'max_products' => 'required|integer|min:1',
            'priority_level' => 'required|integer|min:1|max:10',
            'badge_text' => 'required|string|max:50',
            'badge_color' => 'required|string|max:7',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $package->update($validated);

        return redirect()->route('admin.promotions.packages.index')
                        ->with('success', 'Promotion package updated successfully!');
    }

    public function destroy(PromotionPackage $package)
    {
        // Soft delete by deactivating instead of deleting (to preserve promotion history)
        $package->update(['is_active' => false]);

        return redirect()->route('admin.promotions.packages.index')
                        ->with('success', 'Promotion package deactivated successfully!');
    }
}
