<?php
session_start();

header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$path = realpath(dirname(__DIR__, 3) . '/services/Model.php');
if (!$path) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Model.php not found',
        'debug' => dirname(__DIR__, 3) . '/services/Model.php'
    ]);
    exit;
}
require_once $path;

date_default_timezone_set('Asia/Dhaka');
$date_time = date('Y-m-d g:i:sA');
$date = date('Y-m-d');
$total_days = date('t');

$obj = new Model();

/** helper JSON responder */
function json_out($status, $message, $extra = [])
{
    echo json_encode(array_merge([
        'status'  => $status,
        'message' => $message
    ], $extra));
    exit;
}


$token        = (int)($_GET['token'] ?? 0);
$postAmount      = trim($_GET['amount'] ?? '');




try {

    // customer data
    $data = $obj->details_by_cond('re_tbl_agent', "ag_id='$token'");
    if (!$data) {
        json_out('error', 'Customer not found.');
    }
    
    $resellerId = $data['entry_by'];
    $resellerBill = $data['re_taka'];
    $monthly_bill = $data['taka'];
    $secretMdisconnect = $data['mikrotik_disconnect'] ;
    $secretBalance = $data['balance'] ;
    $secretName = $data['ip'] ;
    $agentName = $data['ag_name'] ;
    
    if ($monthly_bill <= 0) {
        json_out('error', 'Invalid monthly bill.');
    }
    
    
    $per_day_bill = round($monthly_bill / $total_days, 2);
    $paidbilldays = round($postAmount / $per_day_bill);
    
    if ($token <= 0 || $paidbilldays <= 0) {
        json_out('error', 'Invalid customer or days.');
    }

    // bill calc
    // $billamount     = round(((float)$data['taka'] / 30) * $paidbilldays);
    // $rechargeamount = round(((float)$data['re_taka'] / 30) * $paidbilldays);
    
    
            
     // paid bill day
    $paidbillrecharge = round(($resellerBill / $total_days) * $paidbilldays);

    // reseller data
    $resellerSingle = $obj->details_by_cond('_reseller_createuser', "UserId='$resellerId'");
    if (!$resellerSingle) {
        json_out('error', 'Reseller info not found.');
    }
    
    $resname = $resellerSingle['UserName'] ;

    $avBal = (float)($resellerSingle['balance'] ?? 0);

    // if ($avBal < $paidbillrecharge) {
    //     json_out('error', 'Sorry, you have insufficient balance!', [
    //         'available_balance' => $avBal,
    //         'required_balance'  => $paidbillrecharge
    //     ]);
    // }

    // Calculate disconnect baseline date
    $dateDifference = (strtotime(date('Y-m-d')) - strtotime($data['mikrotik_disconnect'])) / (60 * 60 * 24);
    $disDate = ($dateDifference > (float)$resellerSingle['freeday']) ? date('Y-m-d') : $data['mikrotik_disconnect'];

    // prepare update agent
    $form_data_re_tbl_agent = [];
    $form_data_re_tbl_agent['paid_amount']     = (float)$data['paid_amount'];
    $form_data_re_tbl_agent['dueadvance']      = (float)$data['dueadvance'];
    $form_data_re_tbl_agent['generate_amount'] = (float)$data['generate_amount'];

    if ((int)$data['billgenerate'] == 0) {
        $form_data_re_tbl_agent['billgenerate'] = 1;
        $form_data_re_tbl_agent['dueadvance'] += $postAmount;
        $form_data_re_tbl_agent['generate_amount'] += $postAmount;
    }

    $newdisconnect = $data['mikrotik_disconnect'];

    if (($paidbillrecharge > 0) && ($postAmount > 0) && ($paidbilldays > 0)) {
        
        
        
        $form_data_re_tbl_agent['connection_date'] = $data['mikrotik_disconnect'];
        $newdisconnect = date('Y-m-d', strtotime($disDate . " +$paidbilldays days"));
        $form_data_re_tbl_agent['mikrotik_disconnect'] = $newdisconnect;

        $form_data_re_tbl_agent['paid_amount'] += $postAmount;
        $form_data_re_tbl_agent['dueadvance']  -= $postAmount;
        $form_data_re_tbl_agent['ag_status']    = 1;
        $resellerNewbalance = $resellerSingle['balance'] + ($postAmount - $paidbillrecharge);
        // Balance update
        $obj->Update_data('_reseller_createuser', [
            'balance' => $resellerNewbalance
        ], "UserId='$resellerId'");

        $obj->Update_data('re_tbl_agent', [
            'balance' => ((float)$data['balance'] + $paidbillrecharge)
        ], "ag_id='$token'");

        // account entries
        $agent = $obj->raw_sql("SELECT * FROM re_tbl_agent WHERE ag_id='$token'");
        $agent = $agent[0] ?? $data;
        
        
        $obj->Insert_data('re_tbl_reseller_account', ['admin_id' => 99, 'reseller_id' => $resellerId, 'amount' => $postAmount, 'type' => 1, 'description' => "Balance added", 'remark' => 'added by bkash', 'entry_by' => 99,  'entry_date' => date('Y-m-d')]);
        $lastracid =  $obj->Insert_data('re_tbl_reseller_account', ['admin_id' => 100, 'reseller_id' => $resellerId, 'amount' => $postAmount, 'type' => 3, 'description' => "Payment receive ", 'remark' => 'added by bkash', 'entry_by' => $resellerId,  'entry_date' => date('Y-m-d')]);
        $obj->Insert_data('re_tbl_account', ['reseller_account_id' => $lastracid, 'reseller_id' => $resellerId, 'acc_amount' =>$postAmount, 'acc_type' => 3, 'acc_description' => "Payment receive From Reseller by Bkash", 'entry_by' => 99,  'entry_date' => date('Y-m-d')]);
        

        $lastresacc = $obj->Insert_data("re_tbl_reseller_account", [
            'reseller_id' => $resellerId,
            'agent_id'    => $token,
            'amount'      => $paidbillrecharge,
            'type'        => 5,
            'description' => "Balance recharge for $paidbilldays days disconnect date $newdisconnect ($agentName / $secretName) by Bkash",
            'entry_by'    => 99,
            'entry_date'  => $date
        ]);

        $obj->Insert_data("re_tbl_account", [
            'agent_id'            => $token,
            'cus_id'              => $data['cus_id'],
            'acc_amount'          => $postAmount,
            'acc_type'            => '3',
            'acc_description'     => "Bill collection at $date_time by Bkash",
            'entry_by'            => 99,
            'entry_date'          => $date,
            'update_by'           => 99,
            'reseller_id'         => $resellerId,
            'reseller_account_id' => $lastresacc
        ]);
    }

    // final statuses
    $form_data_re_tbl_agent['bill_status']    = 1;
    $form_data_re_tbl_agent['pay_status']     = 0;
    $form_data_re_tbl_agent['payment_status'] = 1;

    $obj->Update_data("re_tbl_agent", $form_data_re_tbl_agent, "ag_id=$token");

    // enable Secret (mikrotik)
    $mikrotikResponse = [
    'status' => false,
    'message' => 'MikroTik configuration not found.'
];

    $mikrotikLoginData = $obj->details_by_cond(
        "re_mikrotik_user",
        "user_id ='$resellerId'"
    );
    
    if (!empty($mikrotikLoginData['mik_ip'])) {
    
        try {
    
            $mikrotik = new Mikrotik(
                $mikrotikLoginData['mik_ip'],
                $mikrotikLoginData['mik_port'],
                $mikrotikLoginData['mik_username'],
                $mikrotikLoginData['mik_password']
            );
    
            if (!empty($mikrotik->connected)) {
    
                $enable = $obj->reEnableSingleSecret(
                    $data['mikrotik_id'],
                    $data['ip']
                );
    
                $mikrotikResponse = [
                    'status' => $enable,
                    'message' => $enable
                        ? 'Secret enabled successfully.'
                        : 'Enable command failed.'
                ];
    
            } else {
    
                $mikrotikResponse = [
                    'status' => false,
                    'message' => 'Unable to connect to MikroTik.',
                    'ip' => $mikrotikLoginData['mik_ip']
                ];
            }
    
        } catch (Throwable $e) {
    
            $mikrotikResponse = [
                'status' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    // SMS
    // $smsPhone = "88" . strval($data['ag_mobile_no'] ?? '');
    // $var_replacement = [
    //     '{CUSTOMER_NAME}' => $data['ag_name'] ?? '',
    //     '{PACKAGE_NAME}' => $data['mb'] ?? '',
    //     '{MONTHLY_BILL}' => $data['taka'] ?? '',
    //     '{CUSTOMER_ID}' => $data['cus_id'] ?? '',
    //     '{IP_ADDRESS}' => $data['ip'] ?? '',
    //     '{PAID_AMOUNT}' => $data['taka'] ?? '',
    //     '{DUE_AMOUNT}' => $data['dueadvance'] ?? ''
    // ];
    // $newCustomerSmsInfo = $obj->rawSqlSingle("SELECT * FROM re_tbl_sms  WHERE reseller_id='$resellerId' AND status=5  AND smshead='active'");
    // if ($newCustomerSmsInfo && isset($newCustomerSmsInfo['smsbody'])) {
    //     $smsBodyTpl = $newCustomerSmsInfo['smsbody'] ?? '';
    //     $smsBody = strtr($smsBodyTpl, $var_replacement);

    //     if (!empty($smsBody) && !empty($smsPhone)) {
    //         try {
    //             $result = $obj->reSendsms($smsPhone, $smsBody, $data['entry_by']);
    //         } catch (\Throwable $th) {
    //             echo $th;
    //         }
    //     }
    // }


    //  JSON success response
    echo json_encode([
        'status' => 'success',
        'mikrotik_response' => $mikrotikResponse
    ]);
    exit;
} catch (Throwable $e) {
    json_out('error', 'Server error: ' . $e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
}
