<?php
// app/Services/NotificationService.php - Multi-channel Notification Service

class NotificationService {
    private $db;
    private $mailer;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->mailer = new Mailer();
    }
    
    /**
     * Create notification
     */
    public function create($user_id, $title, $message, $type = 'info', $category = 'system', $link = null) {
        $sql = "INSERT INTO notifications (user_id, title, message, type, category, link, is_read, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, 0, NOW())";
        
        $result = $this->db->execute($sql, [$user_id, $title, $message, $type, $category, $link]);
        
        return $result ? $this->db->lastInsertId() : false;
    }
    
    /**
     * Send order notification to customer
     */
    public function notifyCustomerOrderCreated($order_id) {
        $order_sql = "SELECT o.*, i.title as item_title, 
                     CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                     u.id as user_id, u.email
                     FROM orders o
                     JOIN items i ON o.item_id = i.id
                     JOIN customers c ON o.customer_id = c.id
                     JOIN users u ON c.user_id = u.id
                     WHERE o.id = ?";
        
        $order = $this->db->fetch($order_sql, [$order_id]);
        
        if (!$order) return false;
        
        // Create in-app notification
        $title = "Order Placed Successfully";
        $message = "Your order #{$order['order_number']} for {$order['item_title']} has been placed successfully.";
        $link = "/customer/orders.php?id={$order_id}";
        
        $this->create($order['user_id'], $title, $message, 'success', 'order', $link);
        
        return true;
    }
    
    /**
     * Send order notification to vendor
     */
    public function notifyVendorNewOrder($order_id) {
        $order_sql = "SELECT o.*, i.title as item_title, v.business_name as vendor_name,
                     CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                     u.id as user_id, u.email as vendor_email
                     FROM orders o
                     JOIN items i ON o.item_id = i.id
                     JOIN vendors v ON o.vendor_id = v.id
                     JOIN users u ON v.user_id = u.id
                     JOIN customers c ON o.customer_id = c.id
                     WHERE o.id = ?";
        
        $order = $this->db->fetch($order_sql, [$order_id]);
        
        if (!$order) return false;
        
        // Create in-app notification
        $title = "New Order Received";
        $message = "You have received a new order #{$order['order_number']} for {$order['item_title']}.";
        $link = "/vendor/orders.php?id={$order_id}";
        
        $this->create($order['user_id'], $title, $message, 'info', 'order', $link);
        
        return true;
    }
    
    /**
     * Notify payment confirmation
     */
    public function notifyPaymentConfirmed($payment_id) {
        $payment_sql = "SELECT p.*, o.order_number, o.customer_id,
                       CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                       u.id as user_id, u.email
                       FROM payments p
                       JOIN orders o ON p.order_id = o.id
                       JOIN customers c ON o.customer_id = c.id
                       JOIN users u ON c.user_id = u.id
                       WHERE p.id = ?";
        
        $payment = $this->db->fetch($payment_sql, [$payment_id]);
        
        if (!$payment) return false;
        
        // Create in-app notification
        $title = "Payment Confirmed";
        $message = "Your payment of " . format_money($payment['amount']) . " for order #{$payment['order_number']} has been confirmed.";
        $link = "/customer/orders.php?id={$payment['order_id']}";
        
        $this->create($payment['user_id'], $title, $message, 'success', 'payment', $link);
        
        return true;
    }
    
    /**
     * Get user notifications
     */
    public function getUserNotifications($user_id, $limit = 20, $unread_only = false) {
        $sql = "SELECT * FROM notifications WHERE user_id = ?";
        $params = [$user_id];
        
        if ($unread_only) {
            $sql .= " AND is_read = 0";
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT ?";
        $params[] = $limit;
        
        return $this->db->fetchAll($sql, $params);
    }
    
    /**
     * Get unread count
     */
    public function getUnreadCount($user_id) {
        $sql = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0";
        $result = $this->db->fetch($sql, [$user_id]);
        return $result['count'] ?? 0;
    }
    
    /**
     * Mark notification as read
     */
    public function markAsRead($notification_id) {
        $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$notification_id]);
    }
    
    /**
     * Mark all as read
     */
    public function markAllAsRead($user_id) {
        $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0";
        return $this->db->execute($sql, [$user_id]);
    }

    /**
     * Notify vendor that they're approved
     */
    public function notifyVendorApproved($vendor_id) {
        $db = Database::getInstance();
        
        // Get vendor details
        $sql = "SELECT v.business_name, v.user_id, u.email 
                FROM vendors v
                LEFT JOIN users u ON v.user_id = u.id
                WHERE v.id = ?";
        $vendor = $db->fetch($sql, [$vendor_id]);
        
        if ($vendor) {
            // Send in-app notification
            $this->create(
                $vendor['user_id'],
                'Vendor Account Approved',
                'Congratulations! Your vendor account has been approved. You can now start listing items.',
                'success',
                'account',
                '/vendor/items.php'
            );
            
            // Send email using template
            $this->mailer->sendVendorApprovalEmail(
                $vendor['email'],
                $vendor['business_name']
            );
        }
    }

    /**
     * Notify vendor that they're rejected
     */
    public function notifyVendorRejected($vendor_id, $reason) {
        $db = Database::getInstance();
        
        // Get vendor details
        $sql = "SELECT v.business_name, v.user_id, u.email 
                FROM vendors v
                LEFT JOIN users u ON v.user_id = u.id
                WHERE v.id = ?";
        $vendor = $db->fetch($sql, [$vendor_id]);
        
        if ($vendor) {
            // Send in-app notification
            $this->create(
                $vendor['user_id'],
                'Vendor Account Rejected',
                'Your vendor account application has been rejected. Reason: ' . $reason,
                'danger',
                'account',
                '/vendor/profile.php'
            );
            
            // Send email using template
            $this->mailer->sendVendorRejectionEmail(
                $vendor['email'],
                $vendor['business_name'],
                $reason
            );
        }
    }

    public function send($user_id, $title, $message, $type = 'info', $category = null, $url = null) 
    {
        $db = Database::getInstance();

        $sql = "INSERT INTO notifications (user_id, title, message, type, category, url, created_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())";

        return $db->execute($sql, [
            $user_id,
            $title,
            $message,
            $type,
            $category,
            $url
        ]);
    }

    /**
     * Send notification to all vendors
     */
    public function sendToVendors($title, $message, $type = 'info') {
        try {
            $vendors = $this->db->fetchAll("SELECT id FROM users WHERE user_type = 'vendor' AND status = 'active'");
            
            $success_count = 0;
            foreach ($vendors as $vendor) {
                if ($this->send($vendor['id'], $title, $message, $type, 'vendor')) {
                    $success_count++;
                }
            }
            
            return $success_count;
        } catch (Exception $e) {
            error_log("Send to vendors failed: " . $e->getMessage());
            return 0;
        }
    }

    /**
     * Send notification to all customers
     */
    public function sendToCustomers($title, $message, $type = 'info') {
        try {
            $customers = $this->db->fetchAll("SELECT id FROM users WHERE user_type = 'customer' AND status = 'active'");
            
            $success_count = 0;
            foreach ($customers as $customer) {
                if ($this->send($customer['id'], $title, $message, $type, 'customer')) {
                    $success_count++;
                }
            }
            
            return $success_count;
        } catch (Exception $e) {
            error_log("Send to customers failed: " . $e->getMessage());
            return 0;
        }
    }

    /**
     * Send notification to all admins
     */
    public function sendToAdmins($title, $message, $type = 'info') {
        try {
            $admins = $this->db->fetchAll("SELECT id FROM users WHERE user_type = 'admin' AND status = 'active'");
            
            $success_count = 0;
            foreach ($admins as $admin) {
                if ($this->send($admin['id'], $title, $message, $type, 'system')) {
                    $success_count++;
                }
            }
            
            return $success_count;
        } catch (Exception $e) {
            error_log("Send to admins failed: " . $e->getMessage());
            return 0;
        }
    }


    /**
     * Notify admin about withdrawal request
     */
    public function notifyWithdrawalRequest($user_id, $amount) {
        try {
            // Get user details
            $user_sql = "SELECT u.email, u.user_type,
                         CASE 
                             WHEN u.user_type = 'vendor' THEN v.business_name
                             WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                             ELSE 'Admin'
                         END as display_name
                         FROM users u
                         LEFT JOIN vendors v ON u.id = v.user_id
                         LEFT JOIN customers c ON u.id = c.user_id
                         WHERE u.id = ?";
            
            $user = $this->db->fetch($user_sql, [$user_id]);
            
            if (!$user) {
                return false;
            }
            
            // Send email to admin
            $mailer = new Mailer();
            $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng';
            
            $subject = "New Withdrawal Request - ₦" . number_format($amount, 2) . " - " . APP_NAME;
            
            $body = "
            <h2>💰 New Withdrawal Request</h2>
            <p>A withdrawal request has been submitted and requires review.</p>
            
            <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #28a745;'>
                <p><strong>User:</strong> {$user['display_name']}</p>
                <p><strong>Type:</strong> " . ucfirst($user['user_type']) . "</p>
                <p><strong>Email:</strong> {$user['email']}</p>
                <p><strong>Amount:</strong> <span style='font-size: 18px; color: #28a745;'>₦" . number_format($amount, 2) . "</span></p>
                <p><strong>Date/Time:</strong> " . date('M d, Y H:i:s') . "</p>
            </div>
            
            <p>Please review and process this request in your admin dashboard.</p>
            <p><a href='" . APP_URL . "/admin/withdrawals.php' style='display: inline-block; padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px;'>View Withdrawal Requests</a></p>
            ";
            
            return $mailer->send($admin_email, $subject, $body);
            
        } catch (Exception $e) {
            error_log("Withdrawal notification error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Notify user about withdrawal status update
     */
    public function notifyWithdrawalStatus($user_id, $amount, $status, $reference) {
        try {
            // Get user details
            $user_sql = "SELECT u.email,
                         CASE 
                             WHEN u.user_type = 'vendor' THEN v.business_name
                             WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                             ELSE 'Admin'
                         END as display_name
                         FROM users u
                         LEFT JOIN vendors v ON u.id = v.user_id
                         LEFT JOIN customers c ON u.id = c.user_id
                         WHERE u.id = ?";
            
            $user = $this->db->fetch($user_sql, [$user_id]);
            
            if (!$user) {
                return false;
            }
            
            $mailer = new Mailer();
            $status_text = ucfirst($status);
            $status_color = $status === 'approved' ? '#28a745' : ($status === 'rejected' ? '#05472A' : '#ffc107');
            
            $subject = "Withdrawal Request {$status_text} - {$reference} - " . APP_NAME;
            
            $body = "
            <h2>Withdrawal Request Update</h2>
            <p>Dear {$user['display_name']},</p>
            <p>Your withdrawal request has been <strong style='color: {$status_color};'>{$status_text}</strong>.</p>
            
            <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;'>
                <p><strong>Reference:</strong> {$reference}</p>
                <p><strong>Amount:</strong> ₦" . number_format($amount, 2) . "</p>
                <p><strong>Status:</strong> <span style='color: {$status_color};'>{$status_text}</span></p>
                <p><strong>Date:</strong> " . date('M d, Y H:i') . "</p>
            </div>
            ";
            
            if ($status === 'approved') {
                $body .= "<p>The funds will be credited to your bank account within 24-48 hours.</p>";
            } elseif ($status === 'rejected') {
                $body .= "<p>If you have any questions about this decision, please contact our support team.</p>";
            }
            
            $body .= "<p>Thank you for using " . APP_NAME . ".</p>";
            
            return $mailer->send($user['email'], $subject, $body);
            
        } catch (Exception $e) {
            error_log("Withdrawal status notification error: " . $e->getMessage());
            return false;
        }
    }
}