<?php
/**
 * SMS Notification Integration Functions
 * Add these functions to your existing code to enable automated notifications
 */

// Include the SMS notification system
require_once '../includes/sms_notification_system.php';

/**
 * Function to send application confirmation SMS when student submits application
 */
function sendApplicationConfirmationSms($studentId, $studentName, $applicationNumber, $mobileNumber) {
    global $pdo;
    
    // Initialize the SMS system
    $smsSystem = new SmsNotificationSystem($pdo);
    
    // Check if application confirmation SMS is enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_application_confirmation'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1') {
        return $smsSystem->sendApplicationNotification($studentId, $studentName, $applicationNumber, $mobileNumber);
    }
    
    return ['success' => false, 'message' => 'Application confirmation SMS not enabled'];
}

/**
 * Function to send fee notification SMS
 */
function sendFeeNotificationSms($studentId, $studentName, $amount, $dueDate, $mobileNumber) {
    global $pdo;
    
    // Initialize the SMS system
    $smsSystem = new SmsNotificationSystem($pdo);
    
    // Check if fee notifications are enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_fee_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1') {
        return $smsSystem->sendFeeNotification($studentId, $studentName, $amount, $dueDate, $mobileNumber);
    }
    
    return ['success' => false, 'message' => 'Fee notification SMS not enabled'];
}

/**
 * Function to send fee due reminder SMS
 */
function sendFeeDueReminderSms($studentId, $studentName, $amount, $dueDate, $mobileNumber) {
    global $pdo;
    
    // Initialize the SMS system
    $smsSystem = new SmsNotificationSystem($pdo);
    
    // Check if fee notifications are enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_fee_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1') {
        return $smsSystem->sendFeeDueReminder($studentId, $studentName, $amount, $dueDate, $mobileNumber);
    }
    
    return ['success' => false, 'message' => 'Fee due reminder SMS not enabled'];
}

/**
 * Function to send result notification SMS
 */
function sendResultNotificationSms($studentId, $studentName, $grade, $gpa, $mobileNumber) {
    global $pdo;
    
    // Initialize the SMS system
    $smsSystem = new SmsNotificationSystem($pdo);
    
    // Check if result notifications are enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_result_notifications'");
    $stmt->execute();
    $result = $stmt->fetch();
    
    if ($result && $result['setting_value'] === '1') {
        return $smsSystem->sendResultNotification($studentId, $studentName, $grade, $gpa, $mobileNumber);
    }
    
    return ['success' => false, 'message' => 'Result notification SMS not enabled'];
}

/**
 * Example integration in application submission process
 */
function processStudentApplication($formData) {
    global $pdo;
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // Insert application data
        $stmt = $pdo->prepare("
            INSERT INTO student_applications (student_name, father_name, mother_name, dob, gender, religion, 
                                            phone, email, address, class_applied, section, guardian_name, 
                                            guardian_phone, admission_year, status, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");
        
        $stmt->execute([
            $formData['student_name'],
            $formData['father_name'],
            $formData['mother_name'],
            $formData['dob'],
            $formData['gender'],
            $formData['religion'],
            $formData['phone'],
            $formData['email'],
            $formData['address'],
            $formData['class_applied'],
            $formData['section'],
            $formData['guardian_name'],
            $formData['guardian_phone'],
            $formData['admission_year']
        ]);
        
        $applicationId = $pdo->lastInsertId();
        $applicationNumber = 'APP-' . date('Y') . '-' . str_pad($applicationId, 6, '0', STR_PAD_LEFT);
        
        // Update application with generated number
        $updateStmt = $pdo->prepare("UPDATE student_applications SET application_number = ? WHERE id = ?");
        $updateStmt->execute([$applicationNumber, $applicationId]);
        
        // Commit transaction
        $pdo->commit();
        
        // Send SMS notification if enabled
        $smsResult = sendApplicationConfirmationSms(
            $applicationId,
            $formData['student_name'],
            $applicationNumber,
            $formData['guardian_phone']
        );
        
        return [
            'success' => true,
            'application_id' => $applicationId,
            'application_number' => $applicationNumber,
            'sms_sent' => $smsResult['success'],
            'message' => 'Application submitted successfully'
        ];
        
    } catch (Exception $e) {
        $pdo->rollback();
        return [
            'success' => false,
            'message' => 'Error submitting application: ' . $e->getMessage()
        ];
    }
}

/**
 * Example usage in fee payment process
 */
function processFeePayment($paymentData) {
    global $pdo;
    
    try {
        // Process fee payment...
        // (your existing fee payment logic)
        
        // After successful payment, send SMS notification
        $stmt = $pdo->prepare("SELECT s.name, s.phone FROM students s WHERE s.id = ?");
        $stmt->execute([$paymentData['student_id']]);
        $student = $stmt->fetch();
        
        if ($student) {
            $smsResult = sendFeeNotificationSms(
                $paymentData['student_id'],
                $student['name'],
                $paymentData['amount'],
                $paymentData['due_date'],
                $student['phone']
            );
            
            return [
                'success' => true,
                'sms_sent' => $smsResult['success'],
                'message' => 'Fee payment processed successfully'
            ];
        }
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Error processing fee payment: ' . $e->getMessage()
        ];
    }
}

/**
 * Example usage in result publication
 */
function publishResult($resultData) {
    global $pdo;
    
    try {
        // Publish result...
        // (your existing result publication logic)
        
        // After result is published, send SMS notification
        $stmt = $pdo->prepare("SELECT s.name, s.phone FROM students s WHERE s.id = ?");
        $stmt->execute([$resultData['student_id']]);
        $student = $stmt->fetch();
        
        if ($student) {
            $smsResult = sendResultNotificationSms(
                $resultData['student_id'],
                $student['name'],
                $resultData['grade'],
                $resultData['gpa'],
                $student['phone']
            );
            
            return [
                'success' => true,
                'sms_sent' => $smsResult['success'],
                'message' => 'Result published successfully'
            ];
        }
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Error publishing result: ' . $e->getMessage()
        ];
    }
}

echo "<h2>SMS Notification Integration Functions</h2>";
echo "<p>Functions ready to integrate with student application, fee, and result processes.</p>";

// Test 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,
    ]);
    
    echo "<p>✅ Database connection successful.</p>";
    echo "<p>✅ SMS notification functions loaded and ready for integration.</p>";
    
} catch (Exception $e) {
    echo "<p style='color:red;'>❌ Database connection error: " . $e->getMessage() . "</p>";
}
?>