<?php

class SmsService
{
    /**
     * Centralized SMS sending and logging method.
     * 
     * @param string $templateName The template name to use
     * @param object $user The user object (must have at least phone and name)
     * @param int $usertypeID
     * @param array|null $data Data for tag replacements
     * @param array|null $replace Tag-value pairs to replace in template
     * @param string|null $adminPhone Optional override phone number
     * @param string|null $module E.g. 'invoice', 'attendance' (for logging)
     * @param string|null $action E.g. 'add', 'edit', 'delete' (for logging)
     * @return mixed Skooly::send() response or false
     */
    private static function processAndSendMessage($templateName, $user, $usertypeID, $data = null, $replace = null, $adminPhone = null, $module = null, $action = null)
    {
        $ci = &get_instance();
        $ci->load->model('mailandsmstemplate_m');
        $ci->load->model('mailandsms_m');

        $mailtemplate = $ci->mailandsmstemplate_m->get_single_mailandsmstemplate(['name' => $templateName]);

        if (!$mailtemplate) {
            return false;
        }

        // Compose the message
        $message = SmsUtils::userConfigSMS($data, $mailtemplate->template, $user, $usertypeID);

        if ($replace) {
            foreach ($replace as $tag => $value) {
                $message = str_replace($tag, $value, $message);
            }
        }

        if ($mailtemplate->status == 1) {
            // Send the SMS
            $result = Skooly::send($adminPhone ?? $user->phone, strip_tags($message), $user->name);

            // Prepare tags for logging
            $tags = $replace ? implode(',', array_keys($replace)) : null;

            // Log the sent SMS
            $smsLog = [
                'usertypeID'        => $user->usertypeID,  // recipient usertype
                'users'             => $user->phone,        // recipient phone
                'recipient_name'    => $user->name,         // recipient name
                'type'              => 'sms',
                'senderusertypeID'  => $senderusertypeID,   // sender usertype
                'senderID'          => $senderID,           // sender id
                'sender_name'       => $sender_name,        // sender name
                'message'           => strip_tags($message),
                'module'            => $module,
                'action'            => $action,
                'template_id'       => $mailtemplate->mailandsmstemplateID,
                'tags'              => $tags,
                'create_date'       => date('Y-m-d H:i:s'),
                'year'              => date('Y'),
            ];
            
            $ci->mailandsms_m->insert_mailandsms($smsLog);

            return $result;
        }

        return false;
    }

    // --------- Example methods, pass module/action where appropriate ---------

    public static function automaticRecharge($user, $usertypeID, $data, $clientMobile, $actionText, $credits)
    {
        return self::processAndSendMessage(
            'Automatic Recharge', $user, $usertypeID, $data,
            array('[recharge_action]' => $actionText, '[recharge_credits]' => $credits),
            $clientMobile, 'wallet', 'automatic_recharge'
        );
    }

    public static function adminAutomaticRecharge($user, $usertypeID, $data, $clientMobile, $actionText, $credits, $clientId)
    {
        return self::processAndSendMessage(
            'Admin Automatic Recharge', $user, $usertypeID, $data,
            array('[recharge_action]' => $actionText, '[recharge_credits]' => $credits, '[client_id]' => $clientId),
            $clientMobile, 'wallet', 'admin_automatic_recharge'
        );
    }

    public static function notifyAdminOnPurchase($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Notify Admin on Purchase', $user, $usertypeID, $data, null, null, 'purchase', 'notify_admin');
    }

    public static function adminGeneralUpdate($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Admin General Update', $user, $usertypeID, $data, null, null, 'admin', 'general_update');
    }

    public static function sendClientNotificationOnPurchase($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Send Client Notification on Purchase', $user, $usertypeID, $data, null, null, 'purchase', 'notify_client');
    }

    public static function daysOverviewSms($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Days Overview SMS', $user, $usertypeID, $data, null, null, 'attendance', 'overview');
    }

    public static function newStudentAdd($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('New Student Add', $user, $usertypeID, $data, null, null, 'student', 'add');
    }

    public static function newInvoice($user, $usertypeID, $data, $fee)
    {
        $ci = &get_instance();
        $ci->load->model('mailandsmstemplate_m');

        $mailtemplate = $ci->mailandsmstemplate_m->get_single_mailandsmstemplate(['name' => 'New Invoice']);

        if (!$mailtemplate) {
            return false;
        }

        $message = SmsUtils::userConfigSMS($data, $mailtemplate->template, $user, $usertypeID);

        $message = str_replace('[fee]', $fee, $message);

        $response = array(
            'message' => strip_tags($message),
            'status' => $mailtemplate->status,
        );

        return $response;
    }

    public static function editInvoice($user, $usertypeID, $data)
    {
        return self::processAndSendMessage('Edit Invoice', $user, $usertypeID, $data, null, null, 'invoice', 'edit');
    }

    public static function invoicePayment($user, $usertypeID, $data, $paid)
    {
        return self::processAndSendMessage('Invoice Payment', $user, $usertypeID, $data, array('[paid]' => $paid), null, 'invoice', 'payment');
    }

    public static function invoiceSendBalanceBySms($user, $usertypeID, $data, $balance)
    {
        return self::processAndSendMessage('Invoice Send Balance by SMS', $user, $usertypeID, $data, array('[invoice_balance]' => $balance), null, 'invoice', 'send_balance');
    }

    public static function walletDeposit($user, $usertypeID, $data, $amount)
    {
        return self::processAndSendMessage('Wallet Deposit', $user, $usertypeID, $data, array('[wallet_amount]' => $amount), null, 'wallet', 'deposit');
    }

    public static function walletWithdraw($user, $usertypeID, $data, $amount)
    {
        return self::processAndSendMessage('Wallet Withdraw', $user, $usertypeID, $data, array('[wallet_amount]' => $amount), null, 'wallet', 'withdraw');
    }

    public static function walletMpesaCredit($user, $usertypeID, $data, $transAmount)
    {
        return self::processAndSendMessage('Wallet Mpesa Credit', $user, $usertypeID, $data, array('[mpesa_amount]' => $transAmount), null, 'wallet', 'mpesa_credit');
    }

    public static function scanCredit($user, $usertypeID, $data, $amount)
    {
        return self::processAndSendMessage('Scan Credit', $user, $usertypeID, $data, array('[wallet_amount]' => $amount), null, 'wallet', 'scan_credit');
    }

    public static function clockIn($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Clock In', $user, $usertypeID, $data, null, null, 'attendance', 'clock_in');
    }

    public static function clockOut($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Clock Out', $user, $usertypeID, $data, null, null, 'attendance', 'clock_out');
    }

    public static function AdminSMSonTeacherClockIn($user, $usertypeID, $data, $adminPhone)
    {
        return self::processAndSendMessage('Admin SMS on Teacher Clock In', $user, $usertypeID, $data, null, $adminPhone, 'attendance', 'clock_in');
    }

    public static function AdminSMSonTeacherClockOut($user, $usertypeID, $data, $adminPhone)
    {
        return self::processAndSendMessage('Admin SMS on Teacher Clock Out', $user, $usertypeID, $data, null, $adminPhone, 'attendance', 'clock_out');
    }

    public static function scanQrClockIn($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Scan QR Clock In', $user, $usertypeID, $data, null, null, 'attendance', 'scan_qr_clock_in');
    }

    public static function scanQrClockOut($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Scan QR Clock Out', $user, $usertypeID, $data, null, null, 'attendance', 'scan_qr_clock_out');
    }

    public static function notClockedInEmergencyAlert($user, $usertypeID, $data = [])
    {
        $ci = &get_instance();
        $ci->load->model('mailandsmstemplate_m');

        $mailtemplate = $ci->mailandsmstemplate_m->get_single_mailandsmstemplate(['name' => 'Not Clocked In (Emergency Alert)']);

        if (!$mailtemplate) {
            return false;
        }

        $message = SmsUtils::userConfigSMS($data, $mailtemplate->template, $user, $usertypeID);

        $response = array(
            'message' => strip_tags($message),
            'status' => $mailtemplate->status,
        );

        return $response;
    }

    public static function salePayment($user, $usertypeID, $data, $paid)
    {
        return self::processAndSendMessage('Sale Payment', $user, $usertypeID, $data, array('[paid]' => $paid), null, 'sale', 'payment');
    }

    public static function newSale($user, $usertypeID, $data, $paid)
    {
        return self::processAndSendMessage('New Sale', $user, $usertypeID, $data, array('[paid]' => $paid), null, 'sale', 'add');
    }

    public static function scanMealBreak($user, $usertypeID, $data, $paid)
    {
        return self::processAndSendMessage('Scan Meal Break', $user, $usertypeID, $data, array('[paid]' => $paid), null, 'meal', 'break');
    }

    public static function scanMealLunch($user, $usertypeID, $data, $paid)
    {
        return self::processAndSendMessage('Scan Meal Lunch', $user, $usertypeID, $data, array('[paid]' => $paid), null, 'meal', 'lunch');
    }

    public static function noticeSms($user, $usertypeID, $data, $notice, $date)
    {
        return self::processAndSendMessage('Notice SMS', $user, $usertypeID, $data, array('[notice]' => $notice, '[notice_date]' => $date), null, 'notice', 'send');
    }

    public static function autopaySMS($user, $usertypeID, $paid, $invoiceId)
    {
        return self::processAndSendMessage('Autopay SMS', $user, $usertypeID, null, array('[paid]' => $paid, '[invoice_id]' => $invoiceId), null, 'invoice', 'autopay');
    }

    public static function studentWithBalanceCard($user, $usertypeID, $data = [])
    {
        $ci = &get_instance();
        $ci->load->model('mailandsmstemplate_m');

        $mailtemplate = $ci->mailandsmstemplate_m->get_single_mailandsmstemplate(['name' => 'Student With Balance Card']);

        if (!$mailtemplate) {
            return false;
        }

        $message = SmsUtils::userConfigSMS($data, $mailtemplate->template, $user, $usertypeID);

        $response = array(
            'message' => strip_tags($message),
            'status' => $mailtemplate->status,
        );

        return $response;
    }

    public static function smsCreditBalanceCard($balance, $data = [])
    {
        $ci = &get_instance();
        $ci->load->model('mailandsmstemplate_m');
        $ci->load->model('systemadmin_m');

        $mailtemplate = $ci->mailandsmstemplate_m->get_single_mailandsmstemplate(['name' => 'SMS Credit Balance Card']);

        if (!$mailtemplate) {
            return false;
        }

        $user = $ci->systemadmin_m->get_single_systemadmin(array('systemadminID' => 1));

        $message = SmsUtils::userConfigSMS($data, $mailtemplate->template, $user, 1);
        $message = str_replace('[sms_balance]', $balance, $message);

        return $mailtemplate->status == 1 ? Skooly::send(get_setting('sms_bal_number'), strip_tags($message), "") : false;
    }

    public static function studentTableFeeBalance($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Student Table Fee Balance', $user, $usertypeID, $data, null, null, 'student', 'table_fee_balance');
    }

    public static function successfulSystemLogin($user, $usertypeID, $data = [])
    {
        return self::processAndSendMessage('Successful System Login', $user, $usertypeID, $data, null, null, 'system', 'login');
    }

    public static function sendOTP($user, $usertypeID, $data, $verificationCode)
    {
        return self::processAndSendMessage('Send OTP Verification Code', $user, $usertypeID, $data, array('[verification_code]' => $verificationCode), null, 'security', 'otp');
    }
}
?>