<?php
/* ============================================================================
   WBMCZ — Notification helper

   Adds a clickable link, a type (for the icon/colour) and a read timestamp to
   every notification, so a user can tap a notification and land on the page it
   is about. Admin can send and delete notifications from admin/notifications.php.
   ============================================================================ */

if (!function_exists('notify_ensure_schema')) {

function notify_ensure_schema($db) {
    static $done = false;
    if ($done) return;
    $done = true;
    $conn = $db->getConnection();

    try {
        $conn->query("CREATE TABLE IF NOT EXISTS notifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            title VARCHAR(255) NOT NULL,
            message TEXT NOT NULL,
            is_read TINYINT(1) DEFAULT 0,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    } catch (\Throwable $e) {}

    foreach ([
        'link'       => "VARCHAR(255) NULL",
        'type'       => "VARCHAR(30) NOT NULL DEFAULT 'general'",
        'read_at'    => "DATETIME NULL",
        'created_by' => "INT NULL",
    ] as $c => $def) {
        try {
            $r = $conn->query("SHOW COLUMNS FROM notifications LIKE '$c'");
            if ($r && $r->num_rows === 0) { $conn->query("ALTER TABLE notifications ADD COLUMN $c $def"); }
        } catch (\Throwable $e) {}
    }
    try { $conn->query("ALTER TABLE notifications ADD INDEX idx_notif_user (user_id, is_read, created_at)"); } catch (\Throwable $e) {}
}

/* type → [label, colour, icon, default link] */
function notify_types() {
    return [
        'general'      => ['General',       'slate',   'fa-bell',              ''],
        'wallet'       => ['Wallet',        'emerald', 'fa-wallet',            'wallet.php#history'],
        'earning'      => ['Earning',       'amber',   'fa-coins',             'earning_report.php'],
        'withdrawal'   => ['Withdrawal',    'blue',    'fa-building-columns',  'wallet.php#to_bank'],
        'order'        => ['Order',         'indigo',  'fa-cart-shopping',     'orders.php'],
        'service'      => ['Service',       'violet',  'fa-layer-group',       'seller/services.php'],
        'kyc'          => ['KYC',           'rose',    'fa-id-card',           'profile.php#kyc'],
        'certificate'  => ['Certificate',   'yellow',  'fa-certificate',       'profile.php#certificate'],
        'subscription' => ['Subscription',  'fuchsia', 'fa-crown',             'subscription.php'],
        'referral'     => ['Referral',      'teal',    'fa-user-plus',         'refer.php'],
        'offer'        => ['Offer',         'pink',    'fa-tags',              ''],
    ];
}

function notify_meta($type) {
    $t = notify_types();
    return $t[$type] ?? $t['general'];
}

/**
 * Send one notification.
 * $link is relative to the site root, e.g. 'wallet.php#to_bank'.
 * Leave it empty to use the default link for that type.
 */
function notify_send($db, $user_id, $title, $message, $type = 'general', $link = '', $created_by = null) {
    notify_ensure_schema($db);
    if ($link === '') { $m = notify_meta($type); $link = $m[3]; }
    try {
        return $db->insert("INSERT INTO notifications (user_id, title, message, type, link, is_read, created_by)
                            VALUES (?,?,?,?,?,0,?)",
            [(int)$user_id, $title, $message, $type, $link, $created_by !== null ? (int)$created_by : null]);
    } catch (\Throwable $e) {
        // Older schema without the new columns
        try { return $db->insert("INSERT INTO notifications (user_id, title, message, is_read) VALUES (?,?,?,0)",
            [(int)$user_id, $title, $message]); } catch (\Throwable $e2) { return false; }
    }
}

/* Send the same notification to many users. Returns how many were sent. */
function notify_send_bulk($db, $user_ids, $title, $message, $type = 'general', $link = '', $created_by = null) {
    $n = 0;
    foreach ($user_ids as $uid) { if (notify_send($db, $uid, $title, $message, $type, $link, $created_by)) $n++; }
    return $n;
}

/* Everyone matching a role — 'all' | 'customer' | 'seller' | 'admin' */
function notify_audience_ids($db, $audience) {
    try {
        if ($audience === 'all') { $r = $db->select("SELECT id FROM users"); }
        else { $r = $db->select("SELECT id FROM users WHERE user_type = ?", [$audience]); }
        return array_map(function ($x) { return (int)$x['id']; }, $r);
    } catch (\Throwable $e) { return []; }
}

/* Resolve a stored link into something usable from the current folder */
function notify_url($link, $base = '') {
    $link = trim((string)$link);
    if ($link === '') return '';
    if (preg_match('#^https?://#i', $link)) return $link;
    return $base . ltrim($link, '/');
}

/* Mark one notification read, then hand back where to go */
function notify_open($db, $notif_id, $user_id) {
    notify_ensure_schema($db);
    try {
        $r = $db->select("SELECT * FROM notifications WHERE id = ? AND user_id = ?", [(int)$notif_id, (int)$user_id]);
        if (empty($r)) return '';
        $db->insert("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ?", [(int)$notif_id]);
        return (string)($r[0]['link'] ?? '');
    } catch (\Throwable $e) { return ''; }
}

function notify_unread_count($db, $user_id) {
    try {
        $r = $db->select("SELECT COUNT(*) n FROM notifications WHERE user_id = ? AND is_read = 0", [(int)$user_id]);
        return !empty($r) ? (int)$r[0]['n'] : 0;
    } catch (\Throwable $e) { return 0; }
}

/* Human "2 hours ago" */
function notify_ago($ts) {
    $diff = time() - strtotime($ts);
    if ($diff < 60)     return 'just now';
    if ($diff < 3600)   return floor($diff / 60) . 'm ago';
    if ($diff < 86400)  return floor($diff / 3600) . 'h ago';
    if ($diff < 604800) return floor($diff / 86400) . 'd ago';
    return date('d M Y', strtotime($ts));
}

} // end function_exists guard
