<?php
require_once __DIR__ . '/BaseModel.php';

/**
 * Notification Management Class
 * Handles SMS, Email, and Push notifications
 */
class Notification extends BaseModel {
    protected $tableName = 'communications';
    protected $tenantColumn = null;
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Send SMS notification
     */
    public function sendSMS($userId, $phoneNumber, $message) {
        // TODO: Integrate with SMS gateway (e.g., Africa's Talking, Twilio)
        // For now, log the notification
        
        $data = [
            'user_id' => $userId,
            'type' => 'SMS',
            'direction' => 'Outbound',
            'recipient' => $phoneNumber,
            'message_body' => $message,
            'status' => 'Queued'
        ];
        
        $notificationId = $this->create($data);
        
        // Simulate sending (replace with actual SMS API call)
        $this->update($notificationId, [
            'status' => 'Sent',
            'sent_at' => date('Y-m-d H:i:s')
        ]);
        
        return $notificationId;
    }
    
    /**
     * Send Email notification
     */
    public function sendEmail($userId, $email, $subject, $message) {
        // TODO: Integrate with email service (e.g., PHPMailer, SendGrid)
        // For now, log the notification
        
        $data = [
            'user_id' => $userId,
            'type' => 'Email',
            'direction' => 'Outbound',
            'recipient' => $email,
            'subject' => $subject,
            'message_body' => $message,
            'status' => 'Queued'
        ];
        
        $notificationId = $this->create($data);
        
        // Simulate sending (replace with actual email sending)
        $this->update($notificationId, [
            'status' => 'Sent',
            'sent_at' => date('Y-m-d H:i:s')
        ]);
        
        return $notificationId;
    }
    
    /**
     * Send rent reminder
     */
    public function sendRentReminder($invoiceId) {
        require_once __DIR__ . '/Invoice.php';
        $invoiceModel = new Invoice();
        $invoice = $invoiceModel->getInvoiceDetails($invoiceId);
        
        if (!$invoice || $invoice['status'] === 'paid') {
            return false;
        }
        
        $tenant = $invoice['tenant'];
        $message = "Dear {$tenant['first_name']}, your rent invoice {$invoice['invoice_number']} of KES " . 
                   number_format($invoice['balance'], 2) . " is due on {$invoice['due_date']}. " .
                   "Please make payment to avoid late fees.";
        
        // Send SMS
        if ($tenant['phone']) {
            $this->sendSMS($tenant['id'], $tenant['phone'], $message);
        }
        
        // Send Email
        if ($tenant['email']) {
            $subject = "Rent Reminder - Invoice {$invoice['invoice_number']}";
            $this->sendEmail($tenant['id'], $tenant['email'], $subject, $message);
        }
        
        return true;
    }
    
    /**
     * Send bulk rent reminders
     */
    public function sendBulkRentReminders($propertyId = null) {
        require_once __DIR__ . '/Invoice.php';
        $invoiceModel = new Invoice();
        $overdueInvoices = $invoiceModel->getOverdueInvoices($propertyId);
        
        $sent = 0;
        foreach ($overdueInvoices as $invoice) {
            if ($this->sendRentReminder($invoice['id'])) {
                $sent++;
            }
        }
        
        return $sent;
    }
    
    /**
     * Send maintenance request notification
     */
    public function sendMaintenanceNotification($requestId, $recipientType = 'manager') {
        $maintenanceModel = new Maintenance();
        $request = $maintenanceModel->getRequestDetails($requestId);
        
        if (!$request) {
            return false;
        }
        
        $message = "New maintenance request {$request['ticket_number']}: {$request['subject']}";
        
        if ($recipientType === 'manager' && $request['property']['manager_id']) {
            $sql = "SELECT id, first_name, email, phone FROM users WHERE id = ?";
            $result = $this->db->query($sql, [$request['property']['manager_id']]);
            $manager = $result->fetch_assoc();
            
            if ($manager) {
                if ($manager['phone']) {
                    $this->sendSMS($manager['id'], $manager['phone'], $message);
                }
                if ($manager['email']) {
                    $this->sendEmail($manager['id'], $manager['email'], "New Maintenance Request", $message);
                }
            }
        }
        
        return true;
    }
    
    /**
     * Send payment confirmation
     */
    public function sendPaymentConfirmation($paymentId) {
        $paymentModel = new Payment();
        $payment = $paymentModel->getById($paymentId);
        
        if (!$payment) {
            return false;
        }
        
        $sql = "SELECT id, first_name, email, phone FROM users WHERE id = ?";
        $result = $this->db->query($sql, [$payment['payer_id']]);
        $payer = $result->fetch_assoc();
        
        $message = "Payment of KES " . number_format($payment['amount'], 2) . 
                   " has been received. Reference: {$payment['transaction_reference']}";
        
        if ($payer['phone']) {
            $this->sendSMS($payer['id'], $payer['phone'], $message);
        }
        
        if ($payer['email']) {
            $this->sendEmail($payer['id'], $payer['email'], "Payment Confirmation", $message);
        }
        
        return true;
    }
}
?>
