<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Ussd;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class UssdController extends Controller
{
    public function index(Request $request)
    {
        $data['ussd'] = auth()->user()->ussds()->select(['id', 'request','response','created_at'])->get();
        return response()->json(['status' => 'success', 'data' => $data]);
    }

    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'ussd_id' => 'required',
            'device_unique_id' => 'required',
            'response' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->messages()], 400);
        }
        $ussd = auth()->user()->ussds()->where('id',  $request->ussd_id)
                    ->where('device_unique_id', $request->device_unique_id)
                    ->first();
        if (!$ussd) {
            return response()->json(['status' => 'error', 'message' => 'USSD record not found'], 404);
        }
        $ussd->response = $request->response;
        $ussd->save();
        return response()->json(['status' => 'success', 'message' => 'USSD Succesfully Updated']);
    }
}
