<?php
/**
 * Automated SMS Notification System for Student Application, Fee, and Result Notifications
 */

class SmsNotificationSystem {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Send SMS notification for student application
     */
    public function sendApplicationNotification($studentId, $studentName, $applicationNumber, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('application_confirmation');
        $message = str_replace(
            ['{name}', '{application_no}'],
            [$studentName, $applicationNumber],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
    
    /**
     * Send SMS notification for fee payment
     */
    public function sendFeeNotification($studentId, $studentName, $amount, $dueDate, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('fee_payment');
        $message = str_replace(
            ['{name}', '{amount}', '{due_date}'],
            [$studentName, $amount, $dueDate],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
    
    /**
     * Send SMS notification for fee due reminder
     */
    public function sendFeeDueReminder($studentId, $studentName, $amount, $dueDate, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('fee_due_reminder');
        $message = str_replace(
            ['{name}', '{amount}', '{due_date}'],
            [$studentName, $amount, $dueDate],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
    
    /**
     * Send SMS notification for result publication
     */
    public function sendResultNotification($studentId, $studentName, $grade, $gpa, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('result_pass');
        $message = str_replace(
            ['{name}', '{grade}', '{gpa}'],
            [$studentName, $grade, $gpa],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
    
    /**
     * Get SMS template from database
     */
    private function getSmsTemplate($templateType) {
        try {
            $stmt = $this->pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
            $stmt->execute(["sms_tpl_$templateType"]);
            $result = $stmt->fetch();
            
            if ($result) {
                return $result['setting_value'];
            }
            
            // Default templates
            $defaults = [
                'application_confirmation' => 'Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you.',
                'fee_payment' => 'Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay on time.',
                'fee_due_reminder' => 'Reminder: Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay soon.',
                'result_pass' => 'Congratulations {name}! You have passed with grade {grade} and GPA {gpa}.',
                'result_fail' => 'Dear {name}, you did not pass this examination. Please try again next time.',
                'bank_transaction' => 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.',
                'bank_transaction_rejection' => 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.'
            ];
            
            return $defaults[$templateType] ?? 'Dear {name}, you have a new update from {school_name}.';
        } catch (Exception $e) {
            return 'Dear {name}, you have a new update from {school_name}.';
        }
    }
    
    /**
     * Send SMS using non-masking helper
     */
    private function sendSms($mobileNumber, $message) {
        // Normalize phone number
        $normalizedNumber = $this->normalizePhoneNumber($mobileNumber);
        
        // Prepare payload
        $payload = [
            'to' => [$normalizedNumber],
            'message' => $message,
            'sender_id' => $this->getConfig('non_musking_sender_id', 'SCHOOL'),
            'api_key' => $this->getConfig('non_musking_api_key'),
            'api_url' => $this->getConfig('non_musking_api_url')
        ];
        
        // Log the SMS attempt
        $this->logSmsAttempt($normalizedNumber, $message, 'pending');
        
        // Attempt to send SMS
        $result = $this->callSmsHelper($payload);
        
        // Update log with result
        $this->logSmsAttempt($normalizedNumber, $message, $result['success'] ? 'sent' : 'failed', $result['raw_response'] ?? '');
        
        return $result;
    }
    
    /**
     * Normalize phone number for Bangladesh
     */
    private function normalizePhoneNumber($number) {
        $number = preg_replace('/[^0-9]/', '', $number);
        
        if (substr($number, 0, 3) === '880') {
            return '+' . $number;
        } elseif (substr($number, 0, 2) === '01') {
            return '+88' . $number;
        } elseif (substr($number, 0, 1) === '1') {
            return '+880' . $number;
        } else {
            return '+' . $number;
        }
    }
    
    /**
     * Get configuration value
     */
    private function getConfig($key, $default = '') {
        try {
            $stmt = $this->pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
            $stmt->execute([$key]);
            $result = $stmt->fetch();
            return $result ? $result['setting_value'] : $default;
        } catch (Exception $e) {
            return $default;
        }
    }
    
    /**
     * Call SMS helper function
     */
    private function callSmsHelper($payload) {
        // Prepare API call to MRAM SMS service
        $apiUrl = $payload['api_url'];
        $apiKey = $payload['api_key'];
        $senderId = $payload['sender_id'];
        $phoneNumber = $payload['to'][0];
        $message = $payload['message'];
        
        // Log SMS API details for debugging
        error_log("SMS API Call - URL: $apiUrl, API Key: " . ($apiKey ? 'SET' : 'NOT SET') . ", Sender ID: $senderId, Phone: $phoneNumber");
        error_log("SMS Message Content: $message");
        
        // Check if required parameters are set
        if (empty($apiUrl) || empty($apiKey)) {
            error_log("SMS Error: Missing API URL or API Key. API URL: '$apiUrl', API Key: '" . ($apiKey ? 'SET' : 'NOT SET') . "'");
            return [
                'success' => false,
                'to' => [],
                'failed' => $payload['to'],
                'method' => 'sms',
                'total_count' => 1,
                'sent_count' => 0,
                'failed_count' => 1,
                'raw_response' => 'Missing API configuration',
                'http_code' => 0
            ];
        }
        
        // Build the API request
        $requestUrl = $apiUrl . '?' . http_build_query([
            'api_key' => $apiKey,
            'type' => 'text',
            'contacts' => $phoneNumber,
            'senderid' => $senderId,
            'msg' => $message
        ], '', '&', PHP_QUERY_RFC3986);
        
        // Make the API call
        $ch = curl_init($requestUrl);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        // Process response
        $success = ($httpCode == 200 && !is_numeric(trim($response)));
        
        return [
            'success' => $success,
            'to' => $success ? $payload['to'] : [],
            'failed' => $success ? [] : $payload['to'],
            'method' => 'sms',
            'total_count' => 1,
            'sent_count' => $success ? 1 : 0,
            'failed_count' => $success ? 0 : 1,
            'raw_response' => $response,
            'http_code' => $httpCode
        ];
    }
    
    /**
     * Log SMS attempt
     */
    private function logSmsAttempt($to, $message, $status, $response = '') {
        try {
            $stmt = $this->pdo->prepare("
                INSERT INTO messages_log (recipient, message_content, status, response_data, created_at) 
                VALUES (?, ?, ?, ?, NOW())
            ");
            $stmt->execute([$to, $message, $status, $response]);
        } catch (Exception $e) {
            // Log error but don't fail the SMS send
            error_log("SMS Logging Error: " . $e->getMessage());
        }
    }
    
    /**
     * Send SMS notification for bank transaction verification
     */
    public function sendBankTransactionNotification($studentId, $studentName, $paidAmount, $dueAmount, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('bank_transaction');
        $message = str_replace(
            ['{name}', '{paid_amount}', '{due_amount}'],
            [$studentName, $paidAmount, $dueAmount],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
    
    /**
     * Send SMS notification for bank transaction rejection
     */
    public function sendBankTransactionRejectionNotification($studentId, $studentName, $amount, $transactionId, $reason, $mobileNumber) {
        // Get SMS template
        $template = $this->getSmsTemplate('bank_transaction_rejection');
        $message = str_replace(
            ['{name}', '{amount}', '{transaction_id}', '{notes}'],
            [$studentName, $amount, $transactionId, $reason],
            $template
        );
        
        return $this->sendSms($mobileNumber, $message);
    }
}

// Initialize the system
$host = 'localhost';
$dbname = 'school_management';
$username = 'root';
$password = 'root';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    
    $smsSystem = new SmsNotificationSystem($pdo);
    
    echo "<h2>Automated SMS Notification System</h2>";
    echo "<p>System ready for student application, fee, and result notifications.</p>";
    
    // Test the system
    echo "<h3>Testing SMS Functions:</h3>";
    echo "<ul>";
    echo "<li>Application Notification: ✅ Ready</li>";
    echo "<li>Fee Payment Notification: ✅ Ready</li>";
    echo "<li>Fee Due Reminder: ✅ Ready</li>";
    echo "<li>Result Notification: ✅ Ready</li>";
    echo "</ul>";
    
    // Update SMS templates in database if they don't exist
    $defaultTemplates = [
        'sms_tpl_application_confirmation' => 'Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you.',
        'sms_tpl_fee_payment' => 'Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay on time.',
        'sms_tpl_fee_due_reminder' => 'Reminder: Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay soon.',
        'sms_tpl_result_pass' => 'Congratulations {name}! You have passed with grade {grade} and GPA {gpa}.',
        'sms_tpl_result_fail' => 'Dear {name}, you did not pass this examination. Please try again next time.',
        'non_musking_templates_general_message' => 'Dear {name}, {message}. Thank you.',
        'non_musking_templates_admission_confirmation' => 'Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you.',
        'sms_tpl_bank_transaction' => 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.',
        'sms_tpl_bank_transaction_rejection' => 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.',
        'non_musking_tpl_bank_transaction' => 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.',
        'non_musking_tpl_bank_transaction_rejection' => 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.'
    ];
    
    $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    foreach ($defaultTemplates as $key => $value) {
        $stmt->execute([$key, $value, $value]);
    }
    
    echo "<p>✅ Default SMS templates updated in database.</p>";
    
} catch (Exception $e) {
    echo "<p style='color:red;'>Error initializing SMS system: " . $e->getMessage() . "</p>";
}
?>