<?php
header('Content-Type: application/json');
session_start();
require_once realpath(dirname(__DIR__, 3) . '/services/Model.php');
$obj = new Model();

$userid = $_SESSION['userid'];
$agentId = $_POST['agent_id'] ?? 0;

if (!$agentId) {
    echo json_encode([
        'status' => 'error',
        'title'  => 'Invalid',
        'message'=> 'Invalid Agent ID'
    ]);
    exit;
}

/* ==== FETCH SINGLE CLIENT ==== */
$client = $obj->details_by_cond(
    "re_tbl_agent",
    "ag_id='$agentId' AND ag_status = 1 AND entry_by='$userid'"
);

if (!$client) {
    echo json_encode([
        'status' => 'warning',
        'title'  => 'Not Found',
        'message'=> 'No due client found'
    ]);
    exit;
}

$mobile = $client['ag_mobile_no'] ?? '';

if (!$mobile) {
    echo json_encode([
        'status' => 'error',
        'title'  => 'No Mobile',
        'message'=> 'Client mobile number not found'
    ]);
    exit;
}

/* ==== SMS TEMPLATE ==== */
$smsTemplate = $obj->details_by_cond("re_tbl_sms", "status='1' AND reseller_id='$userid' AND smshead='active'");
$sms_body = $smsTemplate['smsbody'] ?? '';

$var_replacement = [
    '{CUSTOMER_NAME}' => $client['ag_name'],
    '{DUE_AMOUNT}'    => $client['taka'],
    '{CUSTOMER_ID}'   => $client['cus_id'],
    '{IP_ADDRESS}'    => $client['ip'],
    '{PACKAGE_NAME}'  => $client['mb'],
];

$message = strtr($sms_body, $var_replacement) . 'Disconnect Date: ' . $client['mikrotik_disconnect'];


// $smsArray[] = [
//     "to" => "88" . $mobile,
//     "message" => $message
// ];

/* ==== SEND SMS ==== */
$result = $obj->reSinglesms($mobile, $message, $userid);

if ($result) {
    echo json_encode([
        'status'  => 'success',
        'title'   => 'Success',
        'message' => 'SMS Sent Successfully'
    ]);
} else {
    echo json_encode([
        'status'  => 'error',
        'title'   => 'Failed',
        'message' => 'SMS sending failed!'
    ]);
}