<?php

namespace App\Http\Controllers;

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

class PackageController extends Controller
{
    public function index()
    {
        $packages = Package::all();
        if ($packages->isEmpty()) {
            // Provide default seeded data for frontend if DB is empty
            $packages = [
                ['id' => 1, 'name' => '3 Rides', 'total_rides' => 3, 'price' => 45.00, 'discount_percentage' => 10, 'valid_days' => 30],
                ['id' => 2, 'name' => '6 Rides', 'total_rides' => 6, 'price' => 80.00, 'discount_percentage' => 20, 'valid_days' => 60],
                ['id' => 3, 'name' => '10 Rides', 'total_rides' => 10, 'price' => 120.00, 'discount_percentage' => 30, 'valid_days' => 90],
            ];
        }

        return response()->json([
            'success' => true,
            'packages' => $packages
        ]);
    }

    public function purchase(Request $request)
    {
        $request->validate([
            'package_id' => 'required|exists:packages,id'
        ]);

        $package = Package::find($request->package_id);

        // Deduct from wallet logic here in a real app...
        
        $request->user()->ridePackages()->create([
            'package_id' => $package->id,
            'rides_remaining' => $package->total_rides,
            'valid_until' => now()->addDays($package->valid_days)
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Package purchased successfully.'
        ]);
    }
}
