<?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';

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

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

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

    /**
     * Insert or update package
     */
    public function insert_or_update(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'validity' => 'required|numeric|min:1',
            'commission_with_avg_amount' => 'required|numeric|min:0',
            'category' => 'required|string|max:100',
            'progress' => 'nullable|numeric|min:0|max:100',
            // status is no longer required
        ]);

        if ($request->id) {
            $model = Package::findOrFail($request->id);
        } else {
            $model = new Package();
        }

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

        // Save package data
        $model->name = $request->name;
        $model->price = $request->price;
        $model->validity = $request->validity;
        $model->commission_with_avg_amount = $request->commission_with_avg_amount;
        $model->category = $request->category;
        $model->progress = $request->progress ?? 0;

        // status optional (default inactive)
        $model->status = $request->status ?? $model->status ?? 'inactive';

        $model->save();

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

    /**
     * Delete package
     */
    public function delete($id)
    {
        $model = Package::findOrFail($id);
        if ($model->photo) {
            deleteImage($model->photo);
        }
        $model->delete();

        return redirect()->route($this->route . '.index')
            ->with('success', 'Item Deleted Successfully.');
    }
}
