<?php
// File: includes/notification_helper.php
// Helper functions untuk sistem notifikasi

class NotificationHelper {
    private $db;
    
    public function __construct($database = null) {
        if ($database) {
            $this->db = $database;
        } else {
            require_once 'database.php';
            $this->db = new Database();
        }
    }
    
    /**
     * Menambahkan notifikasi baru untuk admin
     */
    public function addNotification($type, $title, $message, $ticketId = null) {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return false;
            }
            
            $stmt = $connection->prepare("
                INSERT INTO admin_notifications (type, title, message, ticket_id, created_at) 
                VALUES (?, ?, ?, ?, NOW())
            ");
            
            return $stmt->execute([$type, $title, $message, $ticketId]);
        } catch (Exception $e) {
            error_log("Error adding notification: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Menambahkan notifikasi untuk tiket baru
     */
    public function notifyNewTicket($ticketId, $ticketNumber, $username, $subject) {
        $title = "Tiket Baru Masuk";
        $message = "Tiket baru #{$ticketNumber} dari {$username}: {$subject}";
        
        return $this->addNotification('new_ticket', $title, $message, $ticketId);
    }
    
    /**
     * Menambahkan notifikasi untuk tiket yang butuh perhatian
     */
    public function notifyUrgentTicket($ticketId, $ticketNumber, $hoursOld) {
        $title = "Tiket Butuh Perhatian";
        $message = "Tiket #{$ticketNumber} sudah {$hoursOld} jam tanpa balasan";
        
        return $this->addNotification('urgent_ticket', $title, $message, $ticketId);
    }
    
    /**
     * Mendapatkan jumlah notifikasi yang belum dibaca
     */
    public function getUnreadCount() {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return 0;
            }
            
            $stmt = $connection->prepare("
                SELECT COUNT(*) as count 
                FROM admin_notifications 
                WHERE is_read = 0
            ");
            
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return (int)$result['count'];
        } catch (Exception $e) {
            error_log("Error getting unread count: " . $e->getMessage());
            return 0;
        }
    }
    
    /**
     * Mendapatkan notifikasi terbaru
     */
    public function getLatestNotifications($limit = 10) {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return [];
            }
            
            $stmt = $connection->prepare("
                SELECT n.*, t.ticket_number 
                FROM admin_notifications n
                LEFT JOIN support_tickets t ON n.ticket_id = t.id
                WHERE n.is_read = 0 
                ORDER BY n.created_at DESC 
                LIMIT ?
            ");
            
            $stmt->execute([$limit]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Error getting latest notifications: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Menandai notifikasi sebagai sudah dibaca
     */
    public function markAsRead($notificationId) {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return false;
            }
            
            $stmt = $connection->prepare("
                UPDATE admin_notifications 
                SET is_read = 1 
                WHERE id = ?
            ");
            
            return $stmt->execute([$notificationId]);
        } catch (Exception $e) {
            error_log("Error marking notification as read: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Menandai semua notifikasi sebagai sudah dibaca
     */
    public function markAllAsRead() {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return false;
            }
            
            $stmt = $connection->prepare("
                UPDATE admin_notifications 
                SET is_read = 1 
                WHERE is_read = 0
            ");
            
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Error marking all notifications as read: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Membersihkan notifikasi lama (lebih dari 30 hari)
     */
    public function cleanOldNotifications() {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return false;
            }
            
            $stmt = $connection->prepare("
                DELETE FROM admin_notifications 
                WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
            ");
            
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Error cleaning old notifications: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Cek tiket yang butuh perhatian (lebih dari 24 jam tanpa balasan)
     */
    public function checkUrgentTickets() {
        try {
            $connection = $this->db->getConnection();
            if (!$connection) {
                return false;
            }
            
            // Cari tiket yang sudah lama tanpa balasan
            $stmt = $connection->prepare("
                SELECT t.id, t.ticket_number, t.created_at,
                       TIMESTAMPDIFF(HOUR, t.created_at, NOW()) as hours_old
                FROM support_tickets t
                LEFT JOIN support_responses r ON t.id = r.ticket_id
                WHERE t.status = 'open' 
                AND r.id IS NULL 
                AND TIMESTAMPDIFF(HOUR, t.created_at, NOW()) >= 24
                AND NOT EXISTS (
                    SELECT 1 FROM admin_notifications 
                    WHERE ticket_id = t.id 
                    AND type = 'urgent_ticket' 
                    AND created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)
                )
            ");
            
            $stmt->execute();
            $urgentTickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Tambahkan notifikasi untuk setiap tiket urgent
            foreach ($urgentTickets as $ticket) {
                $this->notifyUrgentTicket(
                    $ticket['id'], 
                    $ticket['ticket_number'], 
                    $ticket['hours_old']
                );
            }
            
            return count($urgentTickets);
        } catch (Exception $e) {
            error_log("Error checking urgent tickets: " . $e->getMessage());
            return false;
        }
    }
}

// Function untuk mudah digunakan
function addTicketNotification($ticketId, $ticketNumber, $username, $subject) {
    $notif = new NotificationHelper();
    return $notif->notifyNewTicket($ticketId, $ticketNumber, $username, $subject);
}

function addReplyNotification($ticketId, $ticketNumber, $message) {
    $notif = new NotificationHelper();
    $title = "Balasan User";
    $fullMessage = "User membalas tiket #{$ticketNumber}: {$message}";
    return $notif->addNotification('reply', $title, $fullMessage, $ticketId);
}