<?php
/**
 * Status Check Cron Job
 * 
 * This script checks for status changes in sender IDs and sends SMS notifications
 * to users when their sender ID status changes (approved or rejected).
 * 
 * Set up this script to run every 5 minutes via cron
 * 
 * @author Deywuro API Team
 */

// Load required files
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utilities/Logger.php';

// Set script execution time limit
set_time_limit(300); // 5 minutes

// Log start of process
Logger::log(Logger::INFO, "Starting sender ID status check cron job");

try {
    // Connect to databases
    $db = Database::getPrimaryConnection();
    $apiDb = Database::getApiConnection();
    
    if (!$db) {
        throw new Exception("Failed to connect to primary database");
    }
    
    if (!$apiDb) {
        throw new Exception("Failed to connect to API database");
    }
    
    // Get sender IDs with status changes
    $query = "
        SELECT si.id, si.user_id, si.sender_id, si.status, si.comment, si.username,
               sir.request_id, sir.notification_sent, u.phone_number, u.email, 
               c.name AS company_name, c.contact_person_email, c.contact_person_phone
        FROM user_sender_ids si
        JOIN sender_id_requests sir ON si.sender_id = sir.sender_id
        JOIN users u ON si.user_id = u.id
        LEFT JOIN companies c ON u.company_id = c.id
        WHERE sir.notification_sent = 0
        AND si.status IN (1, 2)  -- 1 = approved, 2 = rejected
        LIMIT 50";
        
    $result = $db->query($query);
    
    if (!$result) {
        throw new Exception("Database query failed: " . $db->error);
    }
    
    // Get SMS API details from config
    $smsUrl = isset($config['sms_api']['url']) ? $config['sms_api']['url'] : '';
    $smsKey = isset($config['sms_api']['key']) ? $config['sms_api']['key'] : '';
    $smsSender = isset($config['sms_api']['sender']) ? $config['sms_api']['sender'] : 'DEYWURO';
    
    while ($row = $result->fetch_assoc()) {
        try {
            // Construct notification message
            $status = $row['status'] == 1 ? 'APPROVED' : 'REJECTED';
            $statusText = $status === 'APPROVED' ? 'approved' : 'rejected';
            $message = "Your Sender ID '{$row['sender_id']}' has been {$statusText}";
            
            // Add rejection reason if available
            if ($status === 'REJECTED' && !empty($row['comment'])) {
                $message .= ". Reason: {$row['comment']}";
            }
            
            // Get user phone number
            $phone = !empty($row['contact_person_phone']) ? $row['contact_person_phone'] : $row['phone_number'];
            
            if (empty($phone)) {
                Logger::log(Logger::WARNING, "No phone number found for sender ID notification", [
                    'sender_id' => $row['sender_id'],
                    'username' => $row['username'],
                    'user_id' => $row['user_id']
                ]);
                continue;
            }
            
            // Format phone number (remove leading zeros, add country code if needed)
            $phone = preg_replace('/^0/', '', $phone);
            if (strlen($phone) <= 9) {
                $phone = '233' . $phone;  // Default to Ghana country code
            }
            
            // SMS API payload
            $smsData = [
                'key' => $smsKey,
                'phone' => $phone,
                'message' => $message,
                'sender' => $smsSender
            ];
            
            Logger::log(Logger::INFO, "Sending SMS notification", [
                'sender_id' => $row['sender_id'],
                'phone' => $phone,
                'status' => $status,
                'request_id' => $row['request_id']
            ]);
            
            $ch = curl_init($smsUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($smsData));
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            
            curl_close($ch);
            
            if ($httpCode != 200 || $error) {
                throw new Exception("SMS API error: $error, HTTP code: $httpCode, Response: $response");
            }
            
            // Also send email notification
            $email = !empty($row['contact_person_email']) ? $row['contact_person_email'] : $row['email'];
            
            if (!empty($email)) {
                $subject = "Sender ID {$statusText} - {$row['sender_id']}";
                $headers = [
                    'From: Deywuro <no-reply@deywuro.com>',
                    'Content-Type: text/html; charset=UTF-8'
                ];
                
                $emailMessage = "
                <html>
                <head>
                    <title>Sender ID {$statusText}</title>
                    <style>
                        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background: #0078d4; color: white; padding: 20px; text-align: center; }
                        .content { padding: 20px; }
                        .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
                        .button { display: inline-block; padding: 10px 20px; background: #0078d4; color: white; text-decoration: none; border-radius: 4px; }
                        table { border-collapse: collapse; width: 100%; }
                        th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
                    </style>
                </head>
                <body>
                    <div class='container'>
                        <div class='header'>
                            <h1>Sender ID " . strtoupper($statusText) . "</h1>
                        </div>
                        <div class='content'>
                            <p>Your Sender ID request has been {$statusText}.</p>
                            
                            <table>
                                <tr>
                                    <th>Sender ID:</th>
                                    <td>{$row['sender_id']}</td>
                                </tr>
                                <tr>
                                    <th>Status:</th>
                                    <td>{$status}</td>
                                </tr>";
                
                if ($status === 'REJECTED' && !empty($row['comment'])) {
                    $emailMessage .= "
                                <tr>
                                    <th>Reason:</th>
                                    <td>{$row['comment']}</td>
                                </tr>";
                }
                
                $emailMessage .= "
                            </table>";
                
                if ($status === 'APPROVED') {
                    $emailMessage .= "
                            <p>You can now use this Sender ID for sending messages through Deywuro platform.</p>";
                } else {
                    $emailMessage .= "
                            <p>You may submit a new Sender ID request or contact our support team if you have questions.</p>";
                }
                
                $emailMessage .= "
                            <p>For any assistance, please contact support@deywuro.com</p>
                        </div>
                        <div class='footer'>
                            <p>&copy; " . date('Y') . " Deywuro. All rights reserved.</p>
                        </div>
                    </div>
                </body>
                </html>";
                
                // Send email notification
                mail($email, $subject, $emailMessage, implode("\r\n", $headers));
                
                Logger::log(Logger::INFO, "Email notification sent", [
                    'sender_id' => $row['sender_id'], 
                    'email' => $email
                ]);
            }
            
            // Update notification status
            $updateQuery = "UPDATE sender_id_requests SET notification_sent = 1 WHERE request_id = ?";
            $stmt = $db->prepare($updateQuery);
            $stmt->bind_param('i', $row['request_id']);
            $stmt->execute();
            $stmt->close();
            
            Logger::log(Logger::INFO, "Notification status updated", [
                'request_id' => $row['request_id'],
                'sender_id' => $row['sender_id']
            ]);
            
        } catch (Exception $e) {
            Logger::log(Logger::ERROR, "Failed to send notification: " . $e->getMessage(), [
                'sender_id' => $row['sender_id'],
                'request_id' => $row['request_id']
            ]);
        }
    }
    
    Logger::log(Logger::INFO, "Completed sender ID status check cron job");
    
} catch (Exception $e) {
    Logger::log(Logger::ERROR, "Error in sender ID status check cron job: " . $e->getMessage());
} 