<?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->send(
                $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
            $subject = "Vendor Account Approved - " . APP_NAME;
            $message = "
                <h2>Congratulations!</h2>
                <p>Dear {$vendor['business_name']},</p>
                <p>Your vendor account has been approved by our admin team.</p>
                <p>You can now:</p>
                <ul>
                    <li>List items for rent</li>
                    <li>Receive bookings from customers</li>
                    <li>Manage your earnings</li>
                </ul>
                <p><a href='" . APP_URL . "/vendor/item-form.php' style='display: inline-block; padding: 10px 20px; background: #27ae60; color: white; text-decoration: none; border-radius: 5px;'>Start Listing Items</a></p>
            ";
            
            $this->mailer->send($vendor['email'], $subject, $message);
        }
    }

    /**
     * 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->send(
                $vendor['user_id'],
                'Vendor Account Rejected',
                'Your vendor account application has been rejected. Reason: ' . $reason,
                'danger',
                'account',
                '/vendor/profile.php'
            );
            
            // Send email
            $subject = "Vendor Account Status - " . APP_NAME;
            $message = "
                <h2>Vendor Application Status</h2>
                <p>Dear {$vendor['business_name']},</p>
                <p>Unfortunately, your vendor account application has been rejected.</p>
                <h3>Rejection Reason:</h3>
                <div style='background: #f8d7da; padding: 15px; border-radius: 5px; border-left: 4px solid #05472A;'>
                    " . nl2br(htmlspecialchars($reason)) . "
                </div>
                <p>If you believe this is a mistake or would like to appeal this decision, please contact our support team.</p>
                <p><a href='" . APP_URL . "/public/contact.php'>Contact Support</a></p>
            ";
            
            $this->mailer->send($vendor['email'], $subject, $message);
        }
    }

    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;
        }
    }
}