<?php

namespace Modules\Notification\Models;

use CodeIgniter\Model;

class UserNotificationModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'user_notifications';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'object';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = [
        'id', 'notification_id', 'user_id', 'is_read', 'read_at', 'sent_at'
    ];

    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = '';

    // Validation
    protected $validationRules      = [
        'notification_id' => 'required|integer',
        'user_id' => 'required|integer'
    ];
    
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks       = true;
    protected $beforeInsert         = [];
    protected $afterInsert          = [];
    protected $beforeUpdate         = [];
    protected $afterUpdate          = [];
    protected $beforeFind           = [];
    protected $afterFind            = [];
    protected $beforeDelete         = [];
    protected $afterDelete          = [];

    /**
     * Get user notifications with notification details
     */
    public function getUserNotifications($userId, $limit = 50, $offset = 0)
    {
        return $this->select('user_notifications.*, notifications.subject, notifications.message, notifications.notification_date')
                    ->join('notifications', 'notifications.id = user_notifications.notification_id')
                    ->where('user_notifications.user_id', $userId)
                    ->orderBy('user_notifications.sent_at', 'DESC')
                    ->limit($limit, $offset)
                    ->findAll();
    }

    /**
     * Get unread notifications count for user
     */
    public function getUnreadCount($userId)
    {
        return $this->where('user_id', $userId)
                    ->where('is_read', 0)
                    ->countAllResults();
    }

    /**
     * Mark notification as read
     */
    public function markAsRead($notificationId, $userId)
    {
        return $this->where('notification_id', $notificationId)
                    ->where('user_id', $userId)
                    ->set([
                        'is_read' => 1,
                        'read_at' => date('Y-m-d H:i:s')
                    ])
                    ->update();
    }

    /**
     * Mark all notifications as read for user
     */
    public function markAllAsRead($userId)
    {
        return $this->where('user_id', $userId)
                    ->where('is_read', 0)
                    ->set([
                        'is_read' => 1,
                        'read_at' => date('Y-m-d H:i:s')
                    ])
                    ->update();
    }

    /**
     * Send notification to multiple users
     */
    public function sendToUsers($notificationId, $userIds)
    {
        $data = [];
        $currentDateTime = date('Y-m-d H:i:s');
        
        foreach ($userIds as $userId) {
            $data[] = [
                'notification_id' => $notificationId,
                'user_id' => $userId,
                'sent_at' => $currentDateTime,
                'created_at' => $currentDateTime,
                'updated_at' => $currentDateTime
            ];
        }
        
        return $this->insertBatch($data);
    }

    /**
     * Get notification delivery statistics
     */
    public function getDeliveryStats($notificationId)
    {
        $stats = [];
        $stats['total_sent'] = $this->where('notification_id', $notificationId)->countAllResults(false);
        $stats['read'] = $this->where('notification_id', $notificationId)->where('is_read', 1)->countAllResults(false);
        $stats['unread'] = $stats['total_sent'] - $stats['read'];
        $stats['read_percentage'] = $stats['total_sent'] > 0 ? round(($stats['read'] / $stats['total_sent']) * 100, 2) : 0;
        
        return $stats;
    }
}
