<?php

namespace App\Http\Controllers\Api;

use App\Helpers\Pdu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class SmsController extends Controller
{
public function decodeSms(Request $request)
{
    $rawdata = $request->all();

    // Log raw request data as plain string
    Log::info('Orgnial Raw data coming from soft data: ' . print_r($rawdata, true));

    $pduString = $request->input('sms');
    $simtty = $request->input('simtty', '');
    $cmgdid = $request->input('CMGDID');
    $imei = $request->input('imei');

    if (!is_string($pduString) || trim($pduString) === '') {
        return response()->json(['error' => "'sms' field must be a non-empty string."], 400);
    }

    try {
        $pduHelper = new Pdu();
        $decodedData = $pduHelper->parseAndDecodeFullPdu($pduString);

        if (isset($decodedData['message'])) {
            $decodedData['message'] = trim(str_replace("\x00", '', $decodedData['message']));
        }

        if (!is_array($decodedData)) {
            $decodedData = ['data' => $decodedData];
        }

        $comPort = $simtty;
        $imeiSerial = $imei;
        $simNumber = $decodedData['sender'] ?? null;
        $smsFrom = $decodedData['sender'] ?? null;
        $smsContent = $decodedData['message'] ?? null;
        $dateTime = $decodedData['timestamp'] ?? now();

        // Log organized SMS transaction data as raw printed string
        Log::info('Organized SMS transaction data: ' . print_r([
            'com_port' => $comPort,
            'imei_serial' => $imeiSerial,
            'sim_number' => $simNumber,
            'sms_from' => $smsFrom,
            'sms_content' => $smsContent,
            'date_time' => $dateTime,
        ], true));

    } catch (\Exception $e) {
        return response()->json(['error' => 'Failed to decode PDU message: ' . $e->getMessage()], 400);
    }

    $command = [];
    if ($simtty !== '') {
        $command[$simtty] = "AT+CMGD={$cmgdid}";
    }

    $response = [
        'status' => 1,
        'decoded' => $decodedData,
        'test' => [
            'status' => 1,
            'test' => 0,
            'updatejs' => 0,
            'modemname' => '',
            'command' => $command,
            'stopask' => [],
        ],
        'updatejs' => 0,
        'modemname' => '',
        'command' => $command,
        'stopask' => [],
    ];

    return response()->json($response);
}


}



