<?php

namespace App\Http\Controllers\Api;

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

class PlanController extends Controller
{
    /**
     * Tampilkan semua plan (Untuk halaman Pricing & Admin)
     */
    public function index()
    {
        $plans = Plan::where('is_active', true)->orderBy('price', 'asc')->get();
        return response()->json($plans);
    }

    /**
     * Simpan plan baru (Admin Only)
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'credit_amount' => 'required|integer|min:0',
            'duration_days' => 'required|integer|min:1',
            'features' => 'nullable|array',
            'is_active' => 'boolean'
        ]);

        $validated['slug'] = Str::slug($request->name);

        $plan = Plan::create($validated);

        return response()->json([
            'message' => 'Plan created successfully',
            'data' => $plan
        ], 201);
    }

    /**
     * Tampilkan detail plan spesifik
     */
    public function show(Plan $plan)
    {
        return response()->json($plan);
    }

    /**
     * Update data plan (Admin Only)
     */
    public function update(Request $request, Plan $plan)
    {
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'price' => 'sometimes|required|numeric|min:0',
            'credit_amount' => 'sometimes|required|integer|min:0',
            'duration_days' => 'sometimes|required|integer|min:1',
            'features' => 'nullable|array',
            'is_active' => 'boolean'
        ]);

        if ($request->has('name')) {
            $validated['slug'] = Str::slug($request->name);
        }

        $plan->update($validated);

        return response()->json([
            'message' => 'Plan updated successfully',
            'data' => $plan
        ]);
    }

    /**
     * Hapus plan (Admin Only)
     */
    public function destroy(Plan $plan)
    {
        $plan->delete();
        return response()->json(['message' => 'Plan deleted successfully']);
    }
}