<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Package;
use App\Models\QuestionCategory;
use Illuminate\Http\Request;

class PackageController extends Controller
{
    public function index()
    {
        $packages = Package::with('questionCategory')->latest()->paginate(15);
        return view('admin.packages.index', compact('packages'));
    }

    public function create()
    {
        $categories = QuestionCategory::all();
        return view('admin.packages.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'unlocks_question_category_id' => 'required|exists:question_categories,id',
            'product_id_apple' => 'nullable|string|max:255',
            'product_id_google' => 'nullable|string|max:255',
            'product_id_gateway' => 'nullable|string|max:255',
            'is_active' => 'nullable|boolean',
        ]);
        
        $validatedData['is_active'] = $request->has('is_active');
        Package::create($validatedData);

        return redirect()->route('admin.packages.index')->with('success', 'تمت إضافة الباقة بنجاح.');
    }

    /**
     * ✅ دالة جديدة: عرض نموذج تعديل الباقة.
     */
    public function edit(Package $package)
    {
        $categories = QuestionCategory::all();
        return view('admin.packages.edit', compact('package', 'categories'));
    }

    /**
     * ✅ دالة جديدة: تحديث بيانات الباقة.
     */
    public function update(Request $request, Package $package)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'unlocks_question_category_id' => 'required|exists:question_categories,id',
            'product_id_apple' => 'nullable|string|max:255',
            'product_id_google' => 'nullable|string|max:255',
            'product_id_gateway' => 'nullable|string|max:255',
            'is_active' => 'nullable|boolean',
        ]);

        $validatedData['is_active'] = $request->has('is_active');
        $package->update($validatedData);

        return redirect()->route('admin.packages.index')->with('success', 'تم تحديث الباقة بنجاح.');
    }

    /**
     * ✅ دالة جديدة: حذف الباقة.
     */
    public function destroy(Package $package)
    {
        $package->delete();
        return redirect()->route('admin.packages.index')->with('success', 'تم حذف الباقة بنجاح.');
    }
}