<?php

require_once BASE_PATH
    . '/app/controllers/owner/OwnerBaseController.php';

require_once BASE_PATH
    . '/app/models/Notification.php';


class OwnerNotificationController extends OwnerBaseController
{
    private Notification $notifications;


    public function __construct()
    {
        $this->requireOwner();

        $this->notifications =
            new Notification();
    }


    /*
    |--------------------------------------------------------------------------
    | DANH SÁCH THÔNG BÁO
    |--------------------------------------------------------------------------
    */

    public function index(): void
    {
        $state =
            in_array(
                $_GET['state'] ?? '',
                [
                    'unread',
                    'read'
                ],
                true
            )
                ? $_GET['state']
                : '';


        $ownerId =
            (int) $_SESSION['user']['id'];


        $notifications =
            $this->notifications
                ->getForUser(
                    $ownerId,
                    $state,
                    50
                );


        $unreadNotificationCount =
            $this->notifications
                ->countUnreadByUser(
                    $ownerId
                );


        require BASE_PATH
            . '/app/views/owner/notifications.php';
    }


    /*
    |--------------------------------------------------------------------------
    | POLL THÔNG BÁO
    |--------------------------------------------------------------------------
    |
    | JavaScript trên Owner sẽ gọi API này mỗi 30 giây.
    |
    | Không cần reload trang.
    |--------------------------------------------------------------------------
    */

    public function poll(): void
    {
        /*
         * Chỉ trả JSON.
         */
        header(
            'Content-Type: application/json; charset=UTF-8'
        );


        $ownerId =
            (int) $_SESSION['user']['id'];


        try {

            /*
             * Lấy các notification chưa đọc gần nhất.
             */
            $items =
                $this->notifications
                    ->getForUser(
                        $ownerId,
                        'unread',
                        10
                    );


            $unreadCount =
                $this->notifications
                    ->countUnreadByUser(
                        $ownerId
                    );


            $data = [];


            foreach ($items as $item) {

                $data[] = [

                    'id' =>
                        (int) (
                            $item['id']
                            ?? 0
                        ),

                    'type' =>
                        (string) (
                            $item['type']
                            ?? ''
                        ),

                    'title' =>
                        (string) (
                            $item['title']
                            ?? 'Thông báo mới'
                        ),

                    'message' =>
                        (string) (
                            $item['message']
                            ?? ''
                        ),

                    'link' =>
                        (string) (
                            $item['link']
                            ?? '?url=owner/notifications'
                        ),

                    'created_at' =>
                        (string) (
                            $item['created_at']
                            ?? ''
                        )

                ];

            }


            echo json_encode(
                [
                    'success' => true,
                    'unread_count' =>
                        (int) $unreadCount,
                    'notifications' =>
                        $data
                ],
                JSON_UNESCAPED_UNICODE
                | JSON_UNESCAPED_SLASHES
            );


        } catch (Throwable $e) {

            http_response_code(500);


            echo json_encode(
                [
                    'success' => false,
                    'unread_count' => 0,
                    'notifications' => []
                ],
                JSON_UNESCAPED_UNICODE
            );

        }


        exit;
    }


    /*
    |--------------------------------------------------------------------------
    | ĐÁNH DẤU 1 THÔNG BÁO ĐÃ ĐỌC
    |--------------------------------------------------------------------------
    */

    public function read(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $ownerId =
            (int) $_SESSION['user']['id'];


        $notification =
            $this->notifications
                ->findOwnedByUser(
                    (int) (
                        $_POST['notification_id']
                        ?? 0
                    ),
                    $ownerId
                );


        if (!$notification) {

            $this->redirect(
                'owner/notifications'
            );

        }


        $this->notifications
            ->markRead(
                (int) $notification['id'],
                $ownerId
            );


        /*
        |--------------------------------------------------------------------------
        | GIỮ NGUYÊN LINK + ID
        |--------------------------------------------------------------------------
        |
        | Ví dụ:
        |
        | ?url=owner/contact&id=15
        |
        | Code cũ chỉ redirect owner/contact
        | nên bị mất id=15.
        |--------------------------------------------------------------------------
        */

        $link =
            trim(
                (string) (
                    $notification['link']
                    ?? ''
                )
            );


        if ($link === '') {

            $this->redirect(
                'owner/notifications'
            );

        }


        /*
         * Chỉ cho phép link nội bộ dạng ?url=...
         * tránh redirect ra website bên ngoài.
         */

        if (
            str_starts_with(
                $link,
                '?url='
            )
        ) {

            header(
                'Location: '
                . BASE_URL
                . '/'
                . $link
            );

            exit;

        }


        $this->redirect(
            'owner/notifications'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | ĐÁNH DẤU TẤT CẢ ĐÃ ĐỌC
    |--------------------------------------------------------------------------
    */

    public function readAll(): void
    {
        $this->requirePost();

        $this->validateCsrf();


        $this->notifications
            ->markAllRead(
                (int) $_SESSION['user']['id']
            );


        $this->flashSuccess(
            'Đã đánh dấu tất cả là đã đọc.'
        );


        $this->redirect(
            'owner/notifications'
        );
    }
}