<?php

namespace App\Http\Controllers\Api;

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

class BillsController extends Controller
{
    public function getHistory(Request $request)
    {
        $history = BillPurchase::where('user_id', $request->user()->id)->latest()->get();
        return response()->json(['success' => true, 'history' => $history]);
    }

    public function buyAirtime(Request $request)
    {
        $request->validate(['provider' => 'required', 'phone' => 'required', 'amount' => 'required|numeric']);
        $bill = BillPurchase::create(['user_id' => $request->user()->id, 'service_type' => 'airtime', 'provider' => $request->provider, 'target_number' => $request->phone, 'amount' => $request->amount, 'reference' => 'BILL-'.uniqid(), 'status' => 'successful']);
        return response()->json(['success' => true, 'message' => 'Airtime purchased successfully.', 'receipt' => $bill]);
    }

    public function buyData(Request $request)
    {
        $request->validate(['provider' => 'required', 'phone' => 'required', 'bundle' => 'required', 'amount' => 'required|numeric']);
        $bill = BillPurchase::create(['user_id' => $request->user()->id, 'service_type' => 'data', 'provider' => $request->provider, 'target_number' => $request->phone, 'amount' => $request->amount, 'reference' => 'DATA-'.uniqid(), 'status' => 'successful']);
        return response()->json(['success' => true, 'message' => 'Data bundle purchased successfully.', 'receipt' => $bill]);
    }

    public function payElectricity(Request $request)
    {
        $request->validate(['provider' => 'required', 'meter_number' => 'required', 'amount' => 'required|numeric']);
        $bill = BillPurchase::create(['user_id' => $request->user()->id, 'service_type' => 'electricity', 'provider' => $request->provider, 'target_number' => $request->meter_number, 'amount' => $request->amount, 'reference' => 'ELEC-'.uniqid(), 'token' => rand(1000, 9999).'-'.rand(1000, 9999).'-'.rand(1000, 9999), 'status' => 'successful']);
        return response()->json(['success' => true, 'message' => 'Electricity token generated.', 'receipt' => $bill]);
    }
}
