<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Notification_model extends CI_Model {

    protected $table = 'notifications';

    public function __construct() {
        parent::__construct();
    }

    /**
     * Get notification by ID
     */
    public function get($id) {
        return $this->db->get_where($this->table, ['id' => $id])->row();
    }

    /**
     * Get notifications for user
     */
    public function get_by_user($user_id, $limit = 20, $offset = 0, $unread_only = false) {
        $this->db->where('user_id', $user_id);
        
        if ($unread_only) {
            $this->db->where('is_read', 0);
        }
        
        $this->db->order_by('created_at', 'DESC');
        $this->db->limit($limit, $offset);
        
        return $this->db->get($this->table)->result();
    }

    /**
     * Count unread notifications
     */
    public function count_unread($user_id) {
        $this->db->where('user_id', $user_id);
        $this->db->where('is_read', 0);
        return $this->db->count_all_results($this->table);
    }

    /**
     * Create notification
     */
    public function create($data) {
        $data['is_read'] = 0;
        $data['created_at'] = date('Y-m-d H:i:s');
        
        if (isset($data['data']) && is_array($data['data'])) {
            $data['data'] = json_encode($data['data']);
        }
        
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    /**
     * Mark notification as read
     */
    public function mark_as_read($id, $user_id) {
        return $this->db->update($this->table, [
            'is_read' => 1,
            'read_at' => date('Y-m-d H:i:s')
        ], ['id' => $id, 'user_id' => $user_id]);
    }

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

    /**
     * Delete notification
     */
    public function delete($id, $user_id) {
        return $this->db->delete($this->table, ['id' => $id, 'user_id' => $user_id]);
    }

    /**
     * Delete all notifications for user
     */
    public function delete_all($user_id) {
        return $this->db->delete($this->table, ['user_id' => $user_id]);
    }

    /**
     * Send transaction notification
     */
    public function send_transaction_notification($user_id, $type, $amount, $reference, $narration = null) {
        $types = [
            'credit' => ['title' => 'Money Received', 'message' => "You received $" . number_format($amount, 2)],
            'debit' => ['title' => 'Money Sent', 'message' => "You sent $" . number_format($amount, 2)],
            'transfer' => ['title' => 'Transfer Successful', 'message' => "Transfer of $" . number_format($amount, 2) . " was successful"],
            'bill_payment' => ['title' => 'Bill Payment', 'message' => "Bill payment of $" . number_format($amount, 2) . " was successful"],
            'card_funding' => ['title' => 'Card Funded', 'message' => "Your card was funded with $" . number_format($amount, 2)]
        ];
        
        $notification = $types[$type] ?? ['title' => 'Transaction', 'message' => "Transaction of $" . number_format($amount, 2)];
        
        if ($narration) {
            $notification['message'] .= ". " . $narration;
        }
        
        return $this->create([
            'user_id' => $user_id,
            'type' => 'transaction',
            'title' => $notification['title'],
            'message' => $notification['message'],
            'data' => ['reference' => $reference, 'amount' => $amount, 'transaction_type' => $type]
        ]);
    }

    /**
     * Send security notification
     */
    public function send_security_notification($user_id, $type, $details = []) {
        $types = [
            'login' => ['title' => 'New Login', 'message' => 'A new login was detected on your account'],
            'password_change' => ['title' => 'Password Changed', 'message' => 'Your password was recently changed'],
            'pin_change' => ['title' => 'PIN Changed', 'message' => 'Your transaction PIN was recently changed'],
            'card_frozen' => ['title' => 'Card Frozen', 'message' => 'Your card has been frozen'],
            'account_frozen' => ['title' => 'Account Frozen', 'message' => 'Your account has been frozen']
        ];
        
        $notification = $types[$type] ?? ['title' => 'Security Alert', 'message' => 'Security activity detected on your account'];
        
        return $this->create([
            'user_id' => $user_id,
            'type' => 'security',
            'title' => $notification['title'],
            'message' => $notification['message'],
            'data' => $details
        ]);
    }

    /**
     * Send general notification
     */
    public function send($user_id, $title, $message, $type = 'general', $data = []) {
        return $this->create([
            'user_id' => $user_id,
            'type' => $type,
            'title' => $title,
            'message' => $message,
            'data' => $data
        ]);
    }

    /**
     * Send bulk notification to all users
     */
    public function send_bulk($title, $message, $type = 'announcement', $user_type = null) {
        $this->load->model('User_model');
        
        $filters = ['status' => 'active'];
        if ($user_type) {
            $filters['user_type'] = $user_type;
        }
        
        $users = $this->User_model->get_all($filters);
        
        foreach ($users as $user) {
            $this->create([
                'user_id' => $user->id,
                'type' => $type,
                'title' => $title,
                'message' => $message
            ]);
        }
        
        return count($users);
    }
}
