<?php

namespace App\Controllers\Api;

use App\Libraries\JwtAuth;
use App\Models\NotificationModel;

class NotificationsController extends BaseApiController
{
    /**
     * GET api/notifications - list notifications for current user (newest first).
     */
    public function index()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $model = model(NotificationModel::class);
        $list  = $model->where('user_id', $user->id)
            ->orderBy('created_at', 'DESC')
            ->findAll(100);
        $data = array_map(static function ($row) {
            return [
                'id'        => (int) $row->id,
                'order_id'  => $row->order_id ? (int) $row->order_id : null,
                'type'      => $row->type ?? 'order_status',
                'title'     => $row->title,
                'body'      => $row->body ?? null,
                'read_at'   => $row->read_at ?? null,
                'created_at' => $row->created_at ?? null,
            ];
        }, $list);
        return $this->success($data);
    }

    /**
     * PATCH api/notifications/(:num) - mark as read. Body: { "read": true }
     */
    public function update(int $id)
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $model = model(NotificationModel::class);
        $row  = $model->where('user_id', $user->id)->find($id);
        if (! $row) {
            return $this->error('Notification not found', 404);
        }
        $json = $this->request->getJSON(true) ?: [];
        if (! empty($json['read'])) {
            $model->update($id, ['read_at' => date('Y-m-d H:i:s')]);
        }
        $row = $model->find($id);
        return $this->success([
            'id'        => (int) $row->id,
            'order_id'  => $row->order_id ? (int) $row->order_id : null,
            'type'      => $row->type ?? 'order_status',
            'title'     => $row->title,
            'body'      => $row->body ?? null,
            'read_at'   => $row->read_at ?? null,
            'created_at' => $row->created_at ?? null,
        ]);
    }
}
