<?php
/**
 * Hostxolo - Notification System
 * Handles WhatsApp, SMS, and Email notifications for critical user actions
 */

require_once __DIR__ . '/../config.php';

class NotificationSystem {
    
    private $db;
    
    public function __construct() {
        $this->db = db();
    }
    
    /**
     * Send notification for new subscription
     */
    public function sendSubscriptionNotification($user_id, $subscription_data) {
        $user = $this->getUser($user_id);
        $message = $this->formatSubscriptionMessage($user, $subscription_data);
        
        // Send Email
        $this->sendEmailNotification(SUPPORT_EMAIL, 'New Subscription Alert', $message);
        
        // Send SMS
        $this->sendSMSNotification(SUPPORT_PHONE, $message);
        
        // Send WhatsApp
        $this->sendWhatsAppNotification(WHATSAPP_NUMBER, $message);
        
        // Log notification
        $this->logNotification('subscription_created', $user_id, $message);
    }
    
    /**
     * Send notification for plan expiry
     */
    public function sendPlanExpiryNotification($user_id, $subscription_data) {
        $user = $this->getUser($user_id);
        $message = $this->formatExpiryMessage($user, $subscription_data);
        
        // Send Email
        $this->sendEmailNotification(SUPPORT_EMAIL, 'Plan Expiry Alert', $message);
        
        // Send SMS
        $this->sendSMSNotification(SUPPORT_PHONE, $message);
        
        // Send WhatsApp
        $this->sendWhatsAppNotification(WHATSAPP_NUMBER, $message);
        
        // Log notification
        $this->logNotification('plan_expired', $user_id, $message);
    }
    
    /**
     * Send notification for new support ticket
     */
    public function sendSupportTicketNotification($user_id, $ticket_data) {
        $user = $this->getUser($user_id);
        $message = $this->formatTicketMessage($user, $ticket_data);
        
        // Send Email
        $this->sendEmailNotification(SUPPORT_EMAIL, 'New Support Ticket', $message);
        
        // Send SMS
        $this->sendSMSNotification(SUPPORT_PHONE, $message);
        
        // Send WhatsApp
        $this->sendWhatsAppNotification(WHATSAPP_NUMBER, $message);
        
        // Log notification
        $this->logNotification('ticket_created', $user_id, $message);
    }
    
    /**
     * Send SMS notification using MSG91
     */
    private function sendSMSNotification($phone, $message) {
        if (SMS_GATEWAY !== 'msg91' || empty(SMS_API_KEY)) {
            return false;
        }
        
        try {
            $url = "https://api.msg91.com/api/v5/flow/";
            $data = [
                'template_id' => 'your_template_id', // Create template in MSG91
                'short_url' => '1',
                'recipients' => [
                    [
                        'mobiles' => ltrim($phone, '+'),
                        'VAR1' => $message
                    ]
                ]
            ];
            
            $headers = [
                'Content-Type: application/json',
                'authkey: ' . SMS_API_KEY
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code == 200) {
                error_log("SMS sent successfully to $phone");
                return true;
            } else {
                error_log("SMS failed: $response");
                return false;
            }
        } catch (Exception $e) {
            error_log("SMS error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send WhatsApp notification using WhatsApp Business API
     */
    private function sendWhatsAppNotification($phone, $message) {
        if (empty(WHATSAPP_API_KEY) || empty(WHATSAPP_PHONE_NUMBER_ID)) {
            return false;
        }
        
        try {
            $url = WHATSAPP_API_URL . WHATSAPP_PHONE_NUMBER_ID . '/messages';
            $data = [
                'messaging_product' => 'whatsapp',
                'to' => ltrim($phone, '+'),
                'type' => 'text',
                'text' => [
                    'body' => $message
                ]
            ];
            
            $headers = [
                'Content-Type: application/json',
                'Authorization: Bearer ' . WHATSAPP_API_KEY
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($http_code == 200) {
                error_log("WhatsApp sent successfully to $phone");
                return true;
            } else {
                error_log("WhatsApp failed: $response");
                return false;
            }
        } catch (Exception $e) {
            error_log("WhatsApp error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send email notification
     */
    private function sendEmailNotification($to, $subject, $message) {
        try {
            require_once __DIR__ . '/email-functions.php';
            
            $html_body = "
            <html>
            <head>
                <title>$subject</title>
            </head>
            <body style='font-family: Arial, sans-serif; padding: 20px;'>
                <div style='max-width: 600px; margin: 0 auto;'>
                    <h2 style='color: #f97316;'>$subject</h2>
                    <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                        $message
                    </div>
                    <hr>
                    <p style='color: #6c757d; font-size: 12px;'>
                        This is an automated notification from " . COMPANY_NAME . "
                    </p>
                </div>
            </body>
            </html>";
            
            return send_email($to, 'Admin', $subject, $html_body);
        } catch (Exception $e) {
            error_log("Email notification error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Format subscription message
     */
    private function formatSubscriptionMessage($user, $subscription) {
        return "
        <h3>🎉 New Subscription Alert!</h3>
        <p><strong>Customer Details:</strong></p>
        <ul>
            <li>Name: {$user['full_name']}</li>
            <li>Email: {$user['email']}</li>
            <li>Phone: {$user['phone']}</li>
        </ul>
        <p><strong>Subscription Details:</strong></p>
        <ul>
            <li>Plan: {$subscription['plan_name']}</li>
            <li>Amount: ₹{$subscription['amount']}</li>
            <li>Start Date: {$subscription['start_date']}</li>
            <li>End Date: {$subscription['end_date']}</li>
        </ul>
        <p><a href='" . BASE_URL . "admin/user-view.php?id={$user['id']}'>View Customer Details</a></p>
        ";
    }
    
    /**
     * Format expiry message
     */
    private function formatExpiryMessage($user, $subscription) {
        return "
        <h3>⚠️ Plan Expiry Alert!</h3>
        <p><strong>Customer Details:</strong></p>
        <ul>
            <li>Name: {$user['full_name']}</li>
            <li>Email: {$user['email']}</li>
            <li>Phone: {$user['phone']}</li>
        </ul>
        <p><strong>Expired Subscription:</strong></p>
        <ul>
            <li>Plan: {$subscription['plan_name']}</li>
            <li>Expired Date: {$subscription['end_date']}</li>
        </ul>
        <p><a href='" . BASE_URL . "admin/user-view.php?id={$user['id']}'>View Customer Details</a></p>
        ";
    }
    
    /**
     * Format support ticket message
     */
    private function formatTicketMessage($user, $ticket) {
        return "
        <h3>🎫 New Support Ticket!</h3>
        <p><strong>Customer Details:</strong></p>
        <ul>
            <li>Name: {$user['full_name']}</li>
            <li>Email: {$user['email']}</li>
            <li>Phone: {$user['phone']}</li>
        </ul>
        <p><strong>Ticket Details:</strong></p>
        <ul>
            <li>Ticket ID: #{$ticket['id']}</li>
            <li>Subject: {$ticket['subject']}</li>
            <li>Priority: {$ticket['priority']}</li>
            <li>Created: {$ticket['created_at']}</li>
        </ul>
        <p><strong>Message:</strong><br>{$ticket['message']}</p>
        <p><a href='" . BASE_URL . "admin/tickets.php'>View Ticket</a></p>
        ";
    }
    
    /**
     * Get user details
     */
    private function getUser($user_id) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            error_log("Error fetching user: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Log notification
     */
    private function logNotification($type, $user_id, $message) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO notifications (user_id, type, message, created_at) 
                VALUES (?, ?, ?, NOW())
            ");
            $stmt->execute([$user_id, $type, $message]);
        } catch (PDOException $e) {
            error_log("Error logging notification: " . $e->getMessage());
        }
    }
}

// Auto-send notifications on critical events
function triggerSubscriptionNotification($user_id, $subscription_data) {
    $notification = new NotificationSystem();
    $notification->sendSubscriptionNotification($user_id, $subscription_data);
}

function triggerExpiryNotification($user_id, $subscription_data) {
    $notification = new NotificationSystem();
    $notification->sendPlanExpiryNotification($user_id, $subscription_data);
}

function triggerTicketNotification($user_id, $ticket_data) {
    $notification = new NotificationSystem();
    $notification->sendSupportTicketNotification($user_id, $ticket_data);
}
