<?php

namespace App\Controllers\Api\Admin;

use App\Models\RewarderNotificationModel;
use CodeIgniter\HTTP\ResponseInterface;

class Notifications extends BaseAdminApiController
{
    public function index(): ResponseInterface
    {
        if ($resp = $this->requirePermission(['notifications_manage', 'notifications_view'])) {
            return $resp;
        }
        $user = $this->user();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }

        $limit = (int) ($this->request->getGet('limit') ?? 20);
        $offset = (int) ($this->request->getGet('offset') ?? 0);
        $unread = (int) ($this->request->getGet('unread') ?? 0);

        $limit = max(1, min(100, $limit));
        $offset = max(0, $offset);

        $model = new RewarderNotificationModel();
        $q = $model->where('user_id', (int) $user->id);
        if ($unread === 1) {
            $q = $q->where('is_read', 0);
        }

        $items = $q->orderBy('id', 'desc')->findAll($limit, $offset);
        $data = array_map(static function ($n) {
            return [
                'id' => (int) $n->id,
                'type' => (string) ($n->type ?? ''),
                'title' => (string) ($n->title ?? ''),
                'body' => (string) ($n->body ?? ''),
                'action_url' => (string) ($n->action_url ?? ''),
                'actionUrl' => (string) ($n->action_url ?? ''),
                'entity_type' => (string) ($n->entity_type ?? ''),
                'entityType' => (string) ($n->entity_type ?? ''),
                'entity_id' => (int) ($n->entity_id ?? 0),
                'entityId' => (int) ($n->entity_id ?? 0),
                'shop_id' => (int) ($n->shop_id ?? 0),
                'shopId' => (int) ($n->shop_id ?? 0),
                'is_read' => (int) ($n->is_read ?? 0),
                'isRead' => (int) ($n->is_read ?? 0),
                'created_at' => (string) ($n->created_at ?? ''),
                'createdAt' => (string) ($n->created_at ?? ''),
                'read_at' => (string) ($n->read_at ?? ''),
                'readAt' => (string) ($n->read_at ?? ''),
            ];
        }, $items ?? []);

        $total = (new RewarderNotificationModel())
            ->where('user_id', (int) $user->id)
            ->countAllResults();
        $unreadCount = (new RewarderNotificationModel())
            ->where('user_id', (int) $user->id)
            ->where('is_read', 0)
            ->countAllResults();

        return $this->ok($data, [
            'limit' => $limit,
            'offset' => $offset,
            'total' => (int) $total,
            'unread_count' => (int) $unreadCount,
            'unreadCount' => (int) $unreadCount,
        ]);
    }

    public function unreadCount(): ResponseInterface
    {
        if ($resp = $this->requirePermission(['notifications_manage', 'notifications_view'])) {
            return $resp;
        }
        $user = $this->user();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }
        $count = (new RewarderNotificationModel())
            ->where('user_id', (int) $user->id)
            ->where('is_read', 0)
            ->countAllResults();
        return $this->ok([
            'count' => (int) $count,
            'unread_count' => (int) $count,
            'unreadCount' => (int) $count,
        ]);
    }

    public function markRead($id): ResponseInterface
    {
        if ($resp = $this->requirePermission('notifications_manage')) {
            return $resp;
        }
        $user = $this->user();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }
        $id = (int) $id;
        if ($id < 1) {
            return $this->fail('Invalid notification id', 400);
        }

        $model = new RewarderNotificationModel();
        $row = $model->where('id', $id)->where('user_id', (int) $user->id)->first();
        if (!$row) {
            return $this->fail('Not found', 404);
        }

        if ((int) $row->is_read !== 1) {
            $model->update($id, ['is_read' => 1, 'read_at' => date('Y-m-d H:i:s')]);
        }

        return $this->ok(['id' => $id]);
    }

    public function markAllRead(): ResponseInterface
    {
        if ($resp = $this->requirePermission('notifications_manage')) {
            return $resp;
        }
        $user = $this->user();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }
        (new RewarderNotificationModel())
            ->where('user_id', (int) $user->id)
            ->where('is_read', 0)
            ->set(['is_read' => 1, 'read_at' => date('Y-m-d H:i:s')])
            ->update();
        return $this->ok(['success' => true]);
    }
}
