<?php
session_start();
$path = realpath(dirname(__DIR__, 3) . '/services/Model.php');
if (!$path) {
    die("Model.php not found! Expected: " . dirname(__DIR__, 3) . '/services/Model.php');
}
require_once $path;

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

$obj = new Model();


$user_id = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0;

$parent_id = isset($_SESSION['parent_id']) ? $_SESSION['parent_id'] : 0;
$id = $user_id;
$resellerSingle = $obj->details_by_cond('_reseller_createuser', "UserId='$id'");




if (isset($_GET['token'])) {
    extract($_GET);
    $token = isset($_GET['token']) ? $_GET['token'] : NULL;
    $data = $obj->details_by_cond('re_tbl_agent', "ag_id='$token'");
    $agentName = $data['ag_name'];
    $agentIp = $data['ip'];

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



    $form_data_re_tbl_agent['paid_amount'] = $data['paid_amount'];
    $form_data_re_tbl_agent['dueadvance'] = $data['dueadvance'];
    $form_data_re_tbl_agent['generate_amount'] = $data['generate_amount'];

    if ($data['billgenerate'] == 0) {
        $form_data_re_tbl_agent['billgenerate'] = 1;
        $form_data_re_tbl_agent['dueadvance'] += $data['taka'];
        $form_data_re_tbl_agent['generate_amount'] += $data['taka'];
        $dueadv = $data['dueadvance'] + $data['taka'];
    } else {
        $dueadv = $data['dueadvance'];
    }

    $pay = $data['taka'];
    $newDueAdv = $dueadv - $pay;

    $payMonth = 1;

    if ($payMonth > 0) {
        $newdisconnect = date('Y-m-d', strtotime($disDate . "+$payMonth months"));
        $form_data_re_tbl_agent['mikrotik_disconnect'] = $newdisconnect;
    }

    if ($resellerSingle['balance'] < ($data['re_taka'] * $payMonth)) {
        return;
        exit;
        die;
    }

    if ($pay > 0) {
        $form_data_re_tbl_agent['paid_amount'] += $pay;
        $form_data_re_tbl_agent['dueadvance'] -= $pay;
    }


    if ($data['ag_status'] == 0) {
        $form_data_re_tbl_agent['ag_status'] = 1;
    }


    if ($payMonth > 0) {
        $obj->Update_data('_reseller_createuser', ['balance' => $resellerSingle['balance'] - ($data['re_taka'] * $payMonth)], "UserId='$id'");
        $obj->Update_data('re_tbl_agent', ['balance' => $data['balance'] + ($data['re_taka'] * $payMonth)], "ag_id='$token'");

        $reFrom = [
            'reseller_id' => $id,
            'agent_id' => $token,
            'amount' => ($data['re_taka'] * $payMonth),
            'type' => 5,
            'description' => "Balance reacharge for $payMonth month disconnect date $newdisconnect ($agentName / $agentIp)",
            'entry_by' => "$user_id",
            'entry_date' => "$date",
        ];
        $lastresacc = $obj->Insert_data("re_tbl_reseller_account", $reFrom);
    }



    $form_data = array(
        'agent_id' => $token,
        'cus_id' => $data['cus_id'],
        'acc_amount' => $data['taka'],
        'acc_type' => '3',
        'acc_description' => !empty($description) ? "$description Bill collection at $date_time" : "Bill collection at $date_time",
        'entry_by' => $id,
        'entry_date' => $date,
        'update_by' => $user_id,
        'reseller_id' => $id,
        'reseller_account_id' => $lastresacc,
    );

    // activity log
    $result = $obj->resellerHistoryLog([
        're_id'        => $user_id,
        'header'       => 'Bill Collection',
        'descriptions' => 'Bill Collection Name: "' . $data['ag_name'] . '" And Cus ID: "' . $data['cus_id'] . '" Collected. Amount: ' . $data['taka'] . '.',
        'type'         => 'insert',
        'ag_id'        => $token,
    ]);


    $obj->Insert_data("re_tbl_account", $form_data);

    $form_data_re_tbl_agent['bill_status'] = 1; //bill paid
    $form_data_re_tbl_agent['pay_status'] = 0; //bill paid
    $form_data_re_tbl_agent['payment_status'] = 1; //bill paid
    $obj->Update_data("`re_tbl_agent`", $form_data_re_tbl_agent, "`re_tbl_agent`.`ag_id`=$token");

    $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='$id' 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, $id);
            } catch (\Throwable $th) {
                echo $th;
            }
        }
    }




    $newDate = $obj->details_by_cond('re_tbl_agent', "ag_id='$token'");

    if (isset($newDate)) {
        // if ($customerSingle) {
        $obj->reEnableSingleSecret($newDate['mikrotik_id'], $newDate['ip']);
        $response['customerActivation'] = 'Customer activated successfully';
        // } 
    } else {
        $response['customerActivation'] = 'Customer not found';
    }

    echo 1;
} else {
    return 0;
}
