<?php

class SmsUtils
{      
    private static $config = [];

    public static function init(array $config): void
    {
        self::$config = $config;
    }

    public static function getConfig(string $key)
    {
        return self::$config[$key] ?? null;
    }

    public static function formatPhone($mobile)
    {
        if (is_array($mobile)) {
            $mobile = reset($mobile);
        }

        if (substr($mobile, 0, 1) == "+") {
            $mobile = str_replace("+", "", $mobile);
        }
        if (substr($mobile, 0, 1) == "0") {
            $mobile = preg_replace("/^0/", "254", $mobile);
        }
        if (substr($mobile, 0, 1) == "7" && strlen($mobile) == 9) {
            $mobile = "254{$mobile}";
        }

        return $mobile;
    }

    public static function createTxtFile(array $recipients, string $fileName): string
    {
        $uploadDir = FCPATH . 'uploads/sms/';
        
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0777, true) && !is_dir($uploadDir)) {
            throw new RuntimeException("Failed to create the directory: " . $uploadDir);
        }

        $filePath = $uploadDir . $fileName;

        $fileHandle = fopen($filePath, 'w');
        if ($fileHandle === false) {
            throw new RuntimeException("Failed to create the file at: " . $filePath);
        }

        fwrite($fileHandle, "Phone\tMessage\n");

        foreach ($recipients as $recipient) {
            $line = self::formatPhone($recipient['phone']) . "\t" . $recipient['message'] . "\n";
            fwrite($fileHandle, $line);
        }

        fclose($fileHandle);

        return $filePath;
    }

    public static function sendSMSGet($request)
    {
        $endpoint = self::getConfig('endpoint');
        if (!$endpoint) {
            throw new RuntimeException("Endpoint is not configured.");
        }

        $url = $endpoint . $request;
        
        $curl = curl_init();
    
        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => array(
            "cache-control: no-cache"
          ),
        ));
        
        $response = curl_exec($curl);
        
        // if ($response === false) {
        //     var_dump(curl_error($curl)); die();
        //     echo "cURL Error: " . curl_error($curl);
        // }

        curl_close($curl);
        $result = json_decode($response,true);
        return $result;
    }

    public static function sendPOSTSMS($postData, $endpoint=null){
        $baseUrl = self::getConfig('endpoint');
        
        if($endpoint){
            $url = $baseUrl.$endpoint;
        }else{
            $url = $baseUrl . "send";
        }
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            error_log("cURL Error: " . $error);
            return false;
        }

        $result = json_decode($response, true);

        return $result;
    }
    
    public static function createTempCSV(array $data): string
    {
        $uploadDir = FCPATH . 'uploads/sms/';

        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0755, true)) {
                throw new RuntimeException('Failed to create SMS directory for file storage.');
            }
        }

        $tempFile = $uploadDir . 'bulk_sms_' . uniqid() . '.csv';

        $fileHandle = fopen($tempFile, 'w');

        if ($fileHandle === false) {
            throw new RuntimeException('Failed to open file for writing.');
        }

        fputcsv($fileHandle, ['Phone', 'Message']);

        foreach ($data as $row) {
            fputcsv($fileHandle, $row);
        }

        fclose($fileHandle);

        return $tempFile;
    }

    public static function saveBatch(array $recipients){
        foreach($recipients as $recipient){
            $smsBatchArray[] = array(
                'usertypeID'        => '0',
                'users'             => $recipient['name'],
                'type'              => ucfirst('automated'),
                'message'           => $recipient['message'],
                'year'              => date('Y'),
                'senderusertypeID'  => 1,
                'senderID'          => self::getConfig('senderID')
            );
        }

        $ci = &get_instance();
        $ci->load->model("mailandsms_m");

        $ci->mailandsms_m->insert_batch_sms_log($smsBatchArray);
    }

    public static function saveSingleSms(string $message, string $name ): void {
        $ci = &get_instance();
        $ci->load->model("mailandsms_m");
    
        $entry = self::prepareDBData($name, $message);
    
        $ci->mailandsms_m->insert_mailandsms($entry);
    }

    public static function prepareDBData($name, $message){
        $stdat = array(
            'usertypeID'        => '0',
            'users'             => $name,
            'type'              => ucfirst('automated'),
            'message'           => $message,
            'year'              => date('Y'),
            'senderusertypeID'  => 1,
            'senderID'          => self::getConfig('senderID')
        );

        return $stdat;
    } 

    public static function userConfigSMS($data, $message, $user, $usertypeID, $schoolyearID = 1)
	{
        $ci = &get_instance();
        $ci->load->model("mailandsmstemplatetag_m");

		if ($user && $usertypeID) {
			$userTags = $ci->mailandsmstemplatetag_m->get_order_by_mailandsmstemplatetag(array('usertypeID' => $usertypeID));

			if ($usertypeID == 2) {
				$userTags = $ci->mailandsmstemplatetag_m->get_order_by_mailandsmstemplatetag(array('usertypeID' => 2));
			} elseif ($usertypeID == 3) {
				$userTags = $ci->mailandsmstemplatetag_m->get_order_by_mailandsmstemplatetag(array('usertypeID' => 3));
			} elseif ($usertypeID == 4) {
				$userTags = $ci->mailandsmstemplatetag_m->get_order_by_mailandsmstemplatetag(array('usertypeID' => 4));
			} else {
				$userTags = $ci->mailandsmstemplatetag_m->get_order_by_mailandsmstemplatetag(array('usertypeID' => 1));
			}

			$message = self::tagConvertor($userTags, $user, $message, 'SMS', $schoolyearID, $data);
			if ($user->phone) {
				return $message;
			} else {
				return '';
			}
		}
	}
    
    public static function tagConvertor($userTags, $user, $message, $sendType, $schoolyearID, $data)
	{   
        $ci = &get_instance();
        $ci->load->model('classes_m');
        $ci->load->model('payment_m');
        $ci->load->model('section_m');
        $ci->load->model('studentgroup_m');
        $ci->load->model('subject_m');  
		$ci->load->model('setting_m'); 
		$ci->load->model('wallet_m'); 
		$ci->load->model("site_m");
		$ci->load->model("studentextend_m");

		if($data == null || empty($data)){
			$data['siteinfos'] = $ci->site_m->get_site();
			$data['allcountry'] = getAllCountry();
		}		

		$inst_info = $ci->setting_m->get_setting(); 
		// ===== AUTO-LOAD STUDENT EXTENDED DATA =====
        // Check if we need to load extended data for ANY student-related tags
        $studentExtendTags = ['[extra_curricular_activities]', '[remarks]'];
        $needsExtendData = false;
        
        // Check if message contains any student extend tags
        foreach ($studentExtendTags as $tag) {
            if (strpos($message, $tag) !== false) {
                $needsExtendData = true;
                break;
            }
        }
        
        // Load extended data if needed and user is a student
        if ($needsExtendData && isset($user->srstudentID)) {
            $studentExtend = $ci->studentextend_m->get_single_studentextend([
                'studentID' => $user->srstudentID
            ]);
            
            // Merge extended fields into user object
            if ($studentExtend) {
                $user->extracurricularactivities = $studentExtend->extracurricularactivities ?? '';
                $user->remarks = $studentExtend->remarks ?? '';
            } else {
                // Set default values if no extend record exists
                $user->extracurricularactivities = '';
                $user->remarks = '';
            }
        }
        // ===== END AUTO-LOAD =====     

		if (customCompute($userTags)) {
			foreach ($userTags as $key => $userTag) {
				if ($userTag->tagname == '[name]') {
					if ($user->name) {
						$message = str_replace('[name]', $user->name, $message);
					} else {
						$message = str_replace('[name]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[designation]') {
					if ($user->designation) {
						$message = str_replace('[designation]', $user->designation, $message);
					} else {
						$message = str_replace('[designation]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[dob]') {
					if ($user->dob) {
						$dob =  date("d M Y", strtotime($user->dob));
						$message = str_replace('[dob]', $dob, $message);
					} else {
						$message = str_replace('[dob]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[gender]') {
					if ($user->sex) {
						$message = str_replace('[gender]', $user->sex, $message);
					} else {
						$message = str_replace('[gender]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[religion]') {
					if ($user->religion) {
						$message = str_replace('[religion]', $user->religion, $message);
					} else {
						$message = str_replace('[religion]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[email]') {
					if ($user->email) {
						$message = str_replace('[email]', $user->email, $message);
					} else {
						$message = str_replace('[email]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[phone]') {
					if ($user->phone) {
						$message = str_replace('[phone]', $user->phone, $message);
					} else {
						$message = str_replace('[phone]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[address]') {
					if ($user->address) {
						$message = str_replace('[address]', $user->address, $message);
					} else {
						$message = str_replace('[address]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[jod]') {
					if ($user->jod) {
						$jod =  date("d M Y", strtotime($user->jod));
						$message = str_replace('[jod]', $jod, $message);
					} else {
						$message = str_replace('[jod]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[username]') {
					if ($user->username) {
						$message = str_replace('[username]', $user->username, $message);
					} else {
						$message = str_replace('[username]', ' ', $message);
					}
				} elseif ($userTag->tagname == "[father's_name]") {
					if ($user->father_name) {
						$message = str_replace("[father's_name]", $user->father_name, $message);
					} else {
						$message = str_replace("[father's_name]", ' ', $message);
					}
				} elseif ($userTag->tagname == "[mother's_name]") {
					if ($user->mother_name) {
						$message = str_replace("[mother's_name]", $user->mother_name, $message);
					} else {
						$message = str_replace("[mother's_name]", ' ', $message);
					}
				} elseif ($userTag->tagname == "[father's_profession]") {
					if ($user->father_profession) {
						$message = str_replace("[father's_profession]", $user->father_profession, $message);
					} else {
						$message = str_replace("[father's_profession]", ' ', $message);
					}
				} elseif ($userTag->tagname == "[mother's_profession]") {
					if ($user->mother_profession) {
						$message = str_replace("[mother's_profession]", $user->mother_profession, $message);
					} else {
						$message = str_replace("[mother's_profession]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[class]') {
					$classes = $ci->classes_m->general_get_classes($user->srclassesID);
					if (customCompute($classes)) {
						$message = str_replace('[class]', $classes->classes, $message);
					} else {
						$message = str_replace('[class]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[roll]') {
					if ($user->srroll) {
						$message = str_replace("[roll]", $user->srroll, $message);
					} else {
						$message = str_replace("[roll]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[country]') {
					if ($user->country) {
						if (isset($data['allcountry'][$user->country])) {
							$message = str_replace("[country]", $data['allcountry'][$user->country], $message);
						} else {
							$message = str_replace("[country]", ' ', $message);
						}
					} else {
						$message = str_replace("[country]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[state]') {
					if ($user->state) {
						$message = str_replace("[state]", $user->state, $message);
					} else {
						$message = str_replace("[state]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[register_no]') {
					if ($user->srregisterNO) {
						$message = str_replace("[register_no]", $user->srregisterNO, $message);
					} else {
						$message = str_replace("[register_no]", ' ', $message);
					}
				}elseif ($userTag->tagname == '[balance]') {
					if ($user->fee_balance) {

						$message = str_replace("[balance]", $user->fee_balance, $message);
					} else {
						$message = str_replace("[balance]", ' ', $message);
					}
                } elseif ($userTag->tagname == '[waived]') {
                    if (isset($data['waived_amount'])) {
                        $message = str_replace("[waived]", $data['waived_amount'], $message);
                    } else {
                        $message = str_replace("[waived]", '0', $message);
                    }
                } elseif ($userTag->tagname == '[waived_amount]') {
                    if (isset($data['waived_amount'])) {
                        $message = str_replace("[waived_amount]", $data['waived_amount'], $message);
                    } else {
                        $message = str_replace("[waived_amount]", '0', $message);
                    }
                } elseif ($userTag->tagname == '[waiver_reason]') {
                    if (isset($data['waiver_reason'])) {
                        $message = str_replace("[waiver_reason]", $data['waiver_reason'], $message);
                    } else {
                        $message = str_replace("[waiver_reason]", 'Not specified', $message);
                    }
                } elseif ($userTag->tagname == '[total_credit]') {
                    $paid = isset($data['paid_amount']) ? $data['paid_amount'] : 0;
                    $waived = isset($data['waived_amount']) ? $data['waived_amount'] : 0;
                    $message = str_replace("[total_credit]", $paid + $waived, $message);

                } elseif ($userTag->tagname == '[feetype]') {
                    if (isset($data['feetype'])) {
                        $message = str_replace("[feetype]", $data['feetype'], $message);
                    } else {
                        $message = str_replace("[feetype]", 'Not specified', $message);
                    }

				} elseif ($userTag->tagname == '[section]') {
					if ($user->srsectionID) {
						$section = $ci->section_m->general_get_section($user->srsectionID);
						if (customCompute($section)) {
							$message = str_replace('[section]', $section->section, $message);
						} else {
							$message = str_replace('[section]', ' ', $message);
						}
					} else {
						$message = str_replace("[section]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[blood_group]') {
					if ($user->bloodgroup && $user->bloodgroup != '0') {
						$message = str_replace("[blood_group]", $user->bloodgroup, $message);
					} else {
						$message = str_replace("[blood_group]", ' ', $message);
					}
				} elseif ($userTag->tagname == '[group]') {
					if ($user->srstudentgroupID && $user->srstudentgroupID != 0) {
						$group = $ci->studentgroup_m->get_studentgroup($user->srstudentgroupID);
						if (customCompute($group)) {
							$message = str_replace('[group]', $group->group, $message);
						} else {
							$message = str_replace('[group]', ' ', $message);
						}
					} else {
						$message = str_replace('[group]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[optional_subject]') {
					if ($user->sroptionalsubjectID && $user->sroptionalsubjectID != 0) {
						$subject = $ci->subject_m->general_get_single_subject(array('subjectID' => $user->sroptionalsubjectID));
						if (customCompute($subject)) {
							$message = str_replace('[optional_subject]', $subject->subject, $message);
						} else {
							$message = str_replace('[optional_subject]', ' ', $message);
						}
					} else {
						$message = str_replace('[optional_subject]', ' ', $message);
					}
				} elseif ($userTag->tagname == '[extra_curricular_activities]') {
                    if (property_exists($user, 'extracurricularactivities') && $user->extracurricularactivities) {
                        $message = str_replace("[extra_curricular_activities]", $user->extracurricularactivities, $message);
                    } else {
                        $message = str_replace("[extra_curricular_activities]", ' ', $message);
                    }
                } elseif ($userTag->tagname == '[remarks]') {
                    if (property_exists($user, 'remarks') && $user->remarks) {
                        $message = str_replace("[remarks]", $user->remarks, $message);
                    } else {
                        $message = str_replace("[remarks]", ' ', $message);
                    }
				} elseif ($userTag->tagname == '[time]') {
					$message = str_replace("[time]", date('H:i:s'), $message);
				} elseif ($userTag->tagname == '[date]') {
					$message = str_replace("[date]", date("d M Y"), $message);
				} elseif ($userTag->tagname == '[instName]') {
					$message = str_replace("[instName]", $inst_info->sname, $message);
				} elseif ($userTag->tagname == '[instPhone]') {
					$message = str_replace("[instPhone]", $inst_info->phone, $message);
				} elseif ($userTag->tagname == '[pay_info]') {
					$message = str_replace("[pay_info]", getTopMessage('top_message'), $message);
				} elseif ($userTag->tagname == '[footer_message]') {
					$message = str_replace("[footer_message]", getTopMessage('footer_message'), $message);
				} elseif ($userTag->tagname == '[todays_present]') {
					$message = str_replace("[todays_present]", getTodaysAttendance(), $message);
				} elseif ($userTag->tagname == '[todays_purchase]') {
					$message = str_replace("[todays_purchase]", getCardData('total_purchases'), $message);
				} elseif ($userTag->tagname == '[todays_sales]') {
					$message = str_replace("[todays_sales]", getCardData('total_sales'), $message);
				} elseif ($userTag->tagname == '[todays_mpesa_cash]') {
					$message = str_replace("[todays_mpesa_cash]", getCardData('mpesa_amount'), $message);
				} elseif ($userTag->tagname == '[todays_wallet]') {
					$message = str_replace("[todays_wallet]", getCardData('wallet_credit'), $message);
				} elseif ($userTag->tagname == '[todays_meals]') {
					$message = str_replace("[todays_meals]", getCardData('lunch'), $message);
				} elseif ($userTag->tagname == '[todays_fees]') {
					$message = str_replace("[todays_fees]", getCardData('total_fees'), $message);
				// } elseif ($userTag->tagname == '[verification_code]') {
				// 	$message = str_replace("[verification_code]", $verificationCode, $message);
				}elseif ($userTag->tagname == '[wallet_balance]') {
					$walletData = $ci->wallet_m->getWallet(array('studentID' => $user->srstudentID));
					if ($walletData) {
						$message = str_replace("[wallet_balance]", $walletData->balance, $message);
					} else {
						$message = str_replace("[wallet_balance]", ' ', $message);
					}
				//Completely removed and replaces the existing result_table
				} elseif ($userTag->tagname == '[result_table]') {
                    // Result table not supported - replaced with empty space
                    $message = str_replace("[result_table]", ' ', $message);
                }
				
			}
		}
		return $message;
	}


}
