<?php
/**
 * Enhanced Admin Notification System
 * 
 * This file contains functions to manage admin notifications for all system events
 * including user registrations, transactions, tickets, account status changes, etc.
 */

/**
 * Get unread notifications count for the admin
 * 
 * @param PDO $db Database connection
 * @param int $admin_id Admin ID
 * @return int Number of unread notifications
 */
function getUnreadAdminNotificationsCount($db, $admin_id) {
    try {
        $stmt = $db->prepare("
            SELECT COUNT(*) FROM admin_notifications 
            WHERE (admin_id = ? OR admin_id IS NULL) AND is_read = 0
        ");
        $stmt->execute([$admin_id]);
        return $stmt->fetchColumn();
    } catch (PDOException $e) {
        error_log("Error in getUnreadAdminNotificationsCount: " . $e->getMessage());
        return 0; // Return 0 on error
    }
}

/**
 * Get recent notifications for the admin
 * 
 * @param PDO $db Database connection
 * @param int $admin_id Admin ID
 * @param int $limit Maximum number of notifications to return
 * @return array Array of notification objects
 */
function getRecentAdminNotifications($db, $admin_id, $limit = 5) {
    try {
        $stmt = $db->prepare("
            SELECT * FROM admin_notifications 
            WHERE (admin_id = ? OR admin_id IS NULL)
            ORDER BY created_at DESC 
            LIMIT ?
        ");
        $stmt->bindParam(1, $admin_id, PDO::PARAM_INT);
        $stmt->bindParam(2, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error in getRecentAdminNotifications: " . $e->getMessage());
        return []; // Return empty array on error
    }
}

/**
 * Get all admin notifications with pagination
 * 
 * @param PDO $db Database connection
 * @param int $admin_id Admin ID
 * @param int $page Page number
 * @param int $per_page Items per page
 * @return array Array containing notifications and pagination info
 */
function getAllAdminNotifications($db, $admin_id, $page = 1, $per_page = 20) {
    try {
        // Calculate offset
        $offset = ($page - 1) * $per_page;
        
        // Get total count
        $count_stmt = $db->prepare("
            SELECT COUNT(*) FROM admin_notifications 
            WHERE (admin_id = ? OR admin_id IS NULL)
        ");
        $count_stmt->execute([$admin_id]);
        $total_count = $count_stmt->fetchColumn();
        
        // Get notifications for current page
        $stmt = $db->prepare("
            SELECT * FROM admin_notifications 
            WHERE (admin_id = ? OR admin_id IS NULL)
            ORDER BY created_at DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt->bindParam(1, $admin_id, PDO::PARAM_INT);
        $stmt->bindParam(2, $per_page, PDO::PARAM_INT);
        $stmt->bindParam(3, $offset, PDO::PARAM_INT);
        $stmt->execute();
        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Calculate pagination info
        $total_pages = ceil($total_count / $per_page);
        
        return [
            'notifications' => $notifications,
            'pagination' => [
                'total_count' => $total_count,
                'total_pages' => $total_pages,
                'current_page' => $page,
                'per_page' => $per_page
            ]
        ];
    } catch (PDOException $e) {
        error_log("Error in getAllAdminNotifications: " . $e->getMessage());
        return [
            'notifications' => [],
            'pagination' => [
                'total_count' => 0,
                'total_pages' => 1,
                'current_page' => 1,
                'per_page' => $per_page
            ]
        ];
    }
}

/**
 * Mark an admin notification as read
 * 
 * @param PDO $db Database connection
 * @param int $notification_id Notification ID
 * @param int $admin_id Admin ID
 * @return bool Success status
 */
function markAdminNotificationAsRead($db, $notification_id, $admin_id) {
    try {
        $stmt = $db->prepare("
            UPDATE admin_notifications 
            SET is_read = 1 
            WHERE id = ? AND (admin_id = ? OR admin_id IS NULL)
        ");
        $stmt->execute([$notification_id, $admin_id]);
        return true;
    } catch (PDOException $e) {
        error_log("Error in markAdminNotificationAsRead: " . $e->getMessage());
        return false;
    }
}

/**
 * Mark all admin notifications as read
 * 
 * @param PDO $db Database connection
 * @param int $admin_id Admin ID
 * @return bool Success status
 */
function markAllAdminNotificationsAsRead($db, $admin_id) {
    try {
        $stmt = $db->prepare("
            UPDATE admin_notifications 
            SET is_read = 1 
            WHERE (admin_id = ? OR admin_id IS NULL) AND is_read = 0
        ");
        $stmt->execute([$admin_id]);
        return true;
    } catch (PDOException $e) {
        error_log("Error in markAllAdminNotificationsAsRead: " . $e->getMessage());
        return false;
    }
}

/**
 * Delete a notification
 * 
 * @param PDO $db Database connection
 * @param int $notification_id Notification ID
 * @param int $admin_id Admin ID
 * @return bool Success status
 */
function deleteAdminNotification($db, $notification_id, $admin_id) {
    try {
        $stmt = $db->prepare("
            DELETE FROM admin_notifications 
            WHERE id = ? AND (admin_id = ? OR admin_id IS NULL)
        ");
        $stmt->execute([$notification_id, $admin_id]);
        return true;
    } catch (PDOException $e) {
        error_log("Error in deleteAdminNotification: " . $e->getMessage());
        return false;
    }
}

/**
 * Delete all read notifications
 * 
 * @param PDO $db Database connection
 * @param int $admin_id Admin ID
 * @return bool Success status
 */
function deleteAllReadAdminNotifications($db, $admin_id) {
    try {
        $stmt = $db->prepare("
            DELETE FROM admin_notifications 
            WHERE (admin_id = ? OR admin_id IS NULL) AND is_read = 1
        ");
        $stmt->execute([$admin_id]);
        return true;
    } catch (PDOException $e) {
        error_log("Error in deleteAllReadAdminNotifications: " . $e->getMessage());
        return false;
    }
}

/**
 * Get notification icon based on type
 * 
 * @param string $type Notification type
 * @return string Icon class name
 */
function getAdminNotificationIcon($type) {
    switch ($type) {
        // User Account Related
        case 'new_user':
            return 'bx-user-plus';
        case 'user_login':
            return 'bx-log-in';
        case 'user_status_change':
            return 'bx-user-check';
        case 'user_password_reset':
            return 'bx-key';
        case 'user_profile_update':
            return 'bx-user-circle';
        case 'user_deleted':
            return 'bx-user-x';
            
        // Transaction Related
        case 'new_transaction':
            return 'bx-transfer';
        case 'deposit':
            return 'bx-money';
        case 'withdrawal':
            return 'bx-money-withdraw';
        case 'transfer':
            return 'bx-transfer-alt';
        case 'balance_adjustment':
            return 'bx-slider';
            
        // Crypto Related
        case 'new_deposit':
            return 'bx-coin';
        case 'deposit_approved':
            return 'bx-check-circle';
        case 'deposit_rejected':
            return 'bx-x-circle';
        case 'crypto_withdrawal':
            return 'bx-coin-stack';
            
        // Ticket Related
        case 'new_ticket':
            return 'bx-message-square-add';
        case 'ticket_reply':
            return 'bx-message-detail';
        case 'ticket_status_change':
            return 'bx-message-alt-detail';
        case 'ticket_closed':
            return 'bx-message-square-x';
            
        // KYC Related
        case 'kyc_submitted':
            return 'bx-id-card';
        case 'kyc_approved':
            return 'bx-check-shield';
        case 'kyc_rejected':
            return 'bx-shield-x';
            
        // System Related
        case 'system_alert':
            return 'bx-error-circle';
        case 'security_alert':
            return 'bx-shield-quarter';
        case 'failed_login':
            return 'bx-lock-alt';
            
        // Default
        default:
            return 'bx-bell';
    }
}

/**
 * Get notification color based on type
 * 
 * @param string $type Notification type
 * @return string Bootstrap color class
 */
function getAdminNotificationColor($type) {
    switch ($type) {
        // User Account Related
        case 'new_user':
            return 'info';
        case 'user_login':
            return 'secondary';
        case 'user_status_change':
            return 'primary';
        case 'user_password_reset':
            return 'warning';
        case 'user_profile_update':
            return 'info';
        case 'user_deleted':
            return 'danger';
            
        // Transaction Related
        case 'new_transaction':
            return 'primary';
        case 'deposit':
            return 'success';
        case 'withdrawal':
            return 'warning';
        case 'transfer':
            return 'info';
        case 'balance_adjustment':
            return 'primary';
            
        // Crypto Related
        case 'new_deposit':
            return 'warning';
        case 'deposit_approved':
            return 'success';
        case 'deposit_rejected':
            return 'danger';
        case 'crypto_withdrawal':
            return 'warning';
            
        // Ticket Related
        case 'new_ticket':
            return 'danger';
        case 'ticket_reply':
            return 'warning';
        case 'ticket_status_change':
            return 'info';
        case 'ticket_closed':
            return 'success';
            
        // KYC Related
        case 'kyc_submitted':
            return 'info';
        case 'kyc_approved':
            return 'success';
        case 'kyc_rejected':
            return 'danger';
            
        // System Related
        case 'system_alert':
            return 'danger';
        case 'security_alert':
            return 'danger';
        case 'failed_login':
            return 'danger';
            
        // Default
        default:
            return 'secondary';
    }
}

/**
 * Create a notification for admin
 * 
 * @param PDO $db Database connection
 * @param string $type Notification type
 * @param string $title Notification title
 * @param string $message Notification message
 * @param string $link Link to redirect when clicked
 * @param int|null $admin_id Specific admin ID or null for all admins
 * @param array $metadata Additional data to store with notification (JSON)
 * @return bool Success status
 */
function createAdminNotification($db, $type, $title, $message, $link = '#', $admin_id = null, $metadata = []) {
    try {
        $stmt = $db->prepare("
            INSERT INTO admin_notifications 
            (admin_id, type, title, message, link, metadata, is_read, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 0, NOW())
        ");
        
        // Convert metadata to JSON if it's not empty
        $metadataJson = !empty($metadata) ? json_encode($metadata) : null;
        
        $stmt->execute([$admin_id, $type, $title, $message, $link, $metadataJson]);
        return true;
    } catch (PDOException $e) {
        error_log("Error in createAdminNotification: " . $e->getMessage());
        return false;
    }
}

/**
 * Create a user registration notification
 * 
 * @param PDO $db Database connection
 * @param int $user_id User ID
 * @param string $name User's name
 * @param string $email User's email
 * @return bool Success status
 */
function notifyAdminNewUser($db, $user_id, $name, $email) {
    $title = "New User Registration";
    $message = "$name ($email) has registered a new account.";
    $link = "view_user.php?id=$user_id";
    $metadata = [
        'user_id' => $user_id,
        'email' => $email
    ];
    
    return createAdminNotification($db, 'new_user', $title, $message, $link, null, $metadata);
}

/**
 * Create a transaction notification
 * 
 * @param PDO $db Database connection
 * @param int $transaction_id Transaction ID
 * @param int $user_id User ID
 * @param string $name User's name
 * @param string $type Transaction type (deposit, withdrawal, transfer)
 * @param float $amount Transaction amount
 * @param string $currency Currency code
 * @return bool Success status
 */
function notifyAdminTransaction($db, $transaction_id, $user_id, $name, $type, $amount, $currency) {
    $formattedAmount = number_format($amount, 2);
    
    switch ($type) {
        case 'deposit':
            $title = "New Deposit";
            $message = "$name deposited $currency $formattedAmount.";
            break;
        case 'withdrawal':
            $title = "New Withdrawal";
            $message = "$name requested a withdrawal of $currency $formattedAmount.";
            break;
        case 'transfer':
            $title = "New Transfer";
            $message = "$name transferred $currency $formattedAmount.";
            break;
        default:
            $title = "New Transaction";
            $message = "$name made a $type transaction of $currency $formattedAmount.";
    }
    
    $link = "transaction_details.php?id=$transaction_id";
    $metadata = [
        'user_id' => $user_id,
        'transaction_id' => $transaction_id,
        'amount' => $amount,
        'currency' => $currency,
        'type' => $type
    ];
    
    return createAdminNotification($db, $type, $title, $message, $link, null, $metadata);
}

/**
 * Create a crypto deposit notification
 * 
 * @param PDO $db Database connection
 * @param int $deposit_id Deposit ID
 * @param int $user_id User ID
 * @param string $name User's name
 * @param float $amount Deposit amount
 * @param string $currency Cryptocurrency code
 * @return bool Success status
 */
function notifyAdminCryptoDeposit($db, $deposit_id, $user_id, $name, $amount, $currency) {
    $formattedAmount = number_format($amount, 8); // Use 8 decimals for crypto
    
    $title = "New Crypto Deposit";
    $message = "$name deposited $formattedAmount $currency.";
    $link = "crypto_deposits.php?id=$deposit_id";
    $metadata = [
        'user_id' => $user_id,
        'deposit_id' => $deposit_id,
        'amount' => $amount,
        'currency' => $currency
    ];
    
    return createAdminNotification($db, 'new_deposit', $title, $message, $link, null, $metadata);
}

/**
 * Create a ticket notification
 * 
 * @param PDO $db Database connection
 * @param int $ticket_id Ticket ID
 * @param int $user_id User ID
 * @param string $name User's name
 * @param string $subject Ticket subject
 * @param string $type Notification type (new_ticket, ticket_reply, ticket_closed)
 * @return bool Success status
 */
function notifyAdminTicket($db, $ticket_id, $user_id, $name, $subject, $type) {
    switch ($type) {
        case 'new_ticket':
            $title = "New Support Ticket";
            $message = "$name created a new ticket: $subject";
            break;
        case 'ticket_reply':
            $title = "New Ticket Reply";
            $message = "$name replied to ticket: $subject";
            break;
        case 'ticket_closed':
            $title = "Ticket Closed";
            $message = "Ticket closed: $subject";
            break;
        case 'ticket_status_change':
            $title = "Ticket Status Changed";
            $message = "Status changed for ticket: $subject";
            break;
        default:
            $title = "Ticket Update";
            $message = "Update on ticket: $subject";
    }
    
    $link = "ticket_details.php?id=$ticket_id";
    $metadata = [
        'user_id' => $user_id,
        'ticket_id' => $ticket_id,
        'subject' => $subject
    ];
    
    return createAdminNotification($db, $type, $title, $message, $link, null, $metadata);
}

/**
 * Create a KYC notification
 * 
 * @param PDO $db Database connection
 * @param int $kyc_id KYC submission ID
 * @param int $user_id User ID
 * @param string $name User's name
 * @param string $type Notification type (kyc_submitted, kyc_approved, kyc_rejected)
 * @return bool Success status
 */
function notifyAdminKYC($db, $kyc_id, $user_id, $name, $type) {
    switch ($type) {
        case 'kyc_submitted':
            $title = "New KYC Submission";
            $message = "$name submitted KYC documents for verification.";
            break;
        case 'kyc_approved':
            $title = "KYC Approved";
            $message = "KYC documents for $name have been approved.";
            break;
        case 'kyc_rejected':
            $title = "KYC Rejected";
            $message = "KYC documents for $name have been rejected.";
            break;
        default:
            $title = "KYC Update";
            $message = "Update on KYC verification for $name.";
    }
    
    $link = "kyc_details.php?id=$kyc_id";
    $metadata = [
        'user_id' => $user_id,
        'kyc_id' => $kyc_id
    ];
    
    return createAdminNotification($db, $type, $title, $message, $link, null, $metadata);
}

/**
 * Create a user status change notification
 * 
 * @param PDO $db Database connection
 * @param int $user_id User ID
 * @param string $name User's name
 * @param string $status New status (active, suspended, closed)
 * @return bool Success status
 */
function notifyAdminUserStatusChange($db, $user_id, $name, $status) {
    $title = "User Status Changed";
    $message = "$name's account status changed to " . ucfirst($status) . ".";
    $link = "view_user.php?id=$user_id";
    $metadata = [
        'user_id' => $user_id,
        'status' => $status
    ];
    
    return createAdminNotification($db, 'user_status_change', $title, $message, $link, null, $metadata);
}

/**
 * Create a security alert notification
 * 
 * @param PDO $db Database connection
 * @param string $alert_type Type of security alert
 * @param string $message Alert message
 * @param array $metadata Additional data about the alert
 * @return bool Success status
 */
function notifyAdminSecurityAlert($db, $alert_type, $message, $metadata = []) {
    $title = "Security Alert: " . ucfirst($alert_type);
    $link = "security_alerts.php";
    
    return createAdminNotification($db, 'security_alert', $title, $message, $link, null, $metadata);
}

/**
 * Create a failed login notification
 * 
 * @param PDO $db Database connection
 * @param string $email Email that was used in the failed attempt
 * @param string $ip_address IP address of the attempt
 * @return bool Success status
 */
function notifyAdminFailedLogin($db, $email, $ip_address) {
    $title = "Failed Login Attempt";
    $message = "Failed login attempt for email: $email from IP: $ip_address";
    $link = "security_logs.php";
    $metadata = [
        'email' => $email,
        'ip_address' => $ip_address
    ];
    
    return createAdminNotification($db, 'failed_login', $title, $message, $link, null, $metadata);
}

/**
 * Create a balance adjustment notification
 * 
 * @param PDO $db Database connection
 * @param int $user_id User ID
 * @param string $name User's name
 * @param float $amount Adjustment amount
 * @param string $currency Currency code
 * @param string $type Adjustment type (credit, debit)
 * @param string $reason Reason for adjustment
 * @return bool Success status
 */
function notifyAdminBalanceAdjustment($db, $user_id, $name, $amount, $currency, $type, $reason) {
    $formattedAmount = number_format($amount, 2);
    
    $title = "Balance Adjustment";
    $message = "Admin performed a $type adjustment of $currency $formattedAmount for $name. Reason: $reason";
    $link = "view_user.php?id=$user_id";
    $metadata = [
        'user_id' => $user_id,
        'amount' => $amount,
        'currency' => $currency,
        'type' => $type,
        'reason' => $reason
    ];
    
    return createAdminNotification($db, 'balance_adjustment', $title, $message, $link, null, $metadata);
}

/**
 * Get pending items counts for admin dashboard
 * 
 * @param PDO $db Database connection
 * @return array Counts of various pending items
 */
function getAdminPendingCounts($db) {
    $counts = [
        'pending_withdrawals' => 0,
        'pending_crypto_deposits' => 0,
        'open_tickets' => 0,
        'pending_kyc' => 0
    ];
    
    try {
        // Pending withdrawals
        $stmt = $db->prepare("SELECT COUNT(*) FROM transactions WHERE type = 'withdrawal' AND status = 'pending'");
        $stmt->execute();
        $counts['pending_withdrawals'] = $stmt->fetchColumn();
        
        // Pending crypto deposits
        $stmt = $db->prepare("SELECT COUNT(*) FROM crypto_deposits WHERE status = 'pending'");
        $stmt->execute();
        $counts['pending_crypto_deposits'] = $stmt->fetchColumn();
        
        // Open tickets
        $stmt = $db->prepare("SELECT COUNT(*) FROM tickets WHERE status = 'open'");
        $stmt->execute();
        $counts['open_tickets'] = $stmt->fetchColumn();
        
        // Pending KYC
        $stmt = $db->prepare("SELECT COUNT(*) FROM kyc_submissions WHERE status = 'pending'");
        $stmt->execute();
        $counts['pending_kyc'] = $stmt->fetchColumn();
    } catch (PDOException $e) {
        error_log("Error in getAdminPendingCounts: " . $e->getMessage());
    }
    
    return $counts;
}
?>
