<?php

namespace App\Http\Controllers\Admin;

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

class PlanController extends Controller
{
    public function index()
    {
        $plans = Plan::latest()->get();
        return view('admin.plans.index', compact('plans'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'role_type' => 'required|in:leasing,member',
            'price' => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'features' => 'required|string',
        ]);

        Plan::create([
            'name' => $request->name,
            'role_type' => $request->role_type,
            'price' => $request->price,
            'duration_days' => $request->duration_days,
            'features_json' => array_map('trim', explode(',', $request->features)),
            'is_active' => true,
        ]);

        return redirect()->route('admin.plans.index')->with('success', 'Paket layanan berhasil dibuat.');
    }

    public function edit(Plan $plan)
    {
        return view('admin.plans.edit', compact('plan'));
    }

    public function update(Request $request, Plan $plan)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'duration_days' => 'required|integer|min:1',
            'features' => 'required|string',
        ]);

        $plan->update([
            'name' => $request->name,
            'price' => $request->price,
            'duration_days' => $request->duration_days,
            'features_json' => array_map('trim', explode(',', $request->features)),
            'is_active' => $request->boolean('is_active'),
        ]);

        return redirect()->route('admin.plans.index')->with('success', 'Paket layanan berhasil diperbarui.');
    }

    public function destroy(Plan $plan)
    {
        $plan->update(['is_active' => false]);
        return back()->with('success', 'Paket dinonaktifkan.');
    }
}
