<?php

namespace App\Http\Controllers\Admin;

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

class PackageController extends Controller
{
    public $route = 'admin.package';

    public function index()
    {
        $packages = Package::orderByDesc('id')->get();
        return view('admin.pages.package.index', compact('packages'));
    }

    public function create($id = null)
    {
        $data = null;
        if ($id) {
            $data = Package::findOrFail($id);
        }
        return view('admin.pages.package.insert', compact('data'));
    }

    public function view($id)
    {
        $data = Package::findOrFail($id);
        return view('admin.pages.package.view', compact('data'));
    }

    public function insert_or_update(Request $request)
    {
        // Validation updated with purchase_limit
        $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'validity' => 'required|numeric|min:1',
            'commission_with_avg_amount' => 'required|numeric|min:0',
            'referral_bonus' => 'nullable|numeric|min:0',
            'purchase_limit' => 'nullable|integer|min:0', // NEW: Purchase Limit Validation
            'category' => 'required|string|max:100',
            'progress' => 'nullable|numeric|min:0|max:100',
            'status' => 'nullable|in:active,inactive',
            'income_mode' => 'required|in:daily,maturity',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        $model = $request->id ? Package::findOrFail($request->id) : new Package();

        $path = uploadImage(false, $request, 'photo', 'upload/package/', 200, 200, $model->photo ?? null);
        if ($path) {
            $model->photo = $path;
        }

        $model->name = $request->name;
        $model->price = $request->price;
        $model->validity = $request->validity;
        $model->commission_with_avg_amount = $request->commission_with_avg_amount;
        $model->referral_bonus = $request->referral_bonus ?? 0; 
        
        // NEW: Save the Purchase Limit from Admin Panel
        $model->purchase_limit = $request->purchase_limit ?? 0; 

        $model->category = $request->category;
        $model->progress = $request->progress ?? 0;
        $model->status = $request->status ?? 'active';
        $model->income_mode = $request->income_mode;   
        
        $model->save();

        return redirect()->route($this->route . '.index')
            ->with('success', $request->id ? 'Package Updated Successfully.' : 'Package Created Successfully.');
    }

    public function delete($id)
    {
        $model = Package::findOrFail($id);
        if ($model->photo) {
            deleteImage($model->photo);
        }
        $model->delete();
        return redirect()->route($this->route . '.index')
            ->with('success', 'Package Deleted Successfully.');
    }
}
