<?php

require_once BASE_PATH . '/app/controllers/customer/CustomerBaseController.php';
require_once BASE_PATH . '/app/models/Notification.php';

class CustomerNotificationController extends CustomerBaseController
{
    private Notification $notificationModel;

    public function __construct()
    {
        $this->requireCustomer();
        $this->notificationModel = new Notification();
    }

    public function index(): void
    {
        $customerId = (int) $_SESSION['user']['id'];
        $state = trim($_GET['state'] ?? '');
        if (!in_array($state, ['', 'unread', 'read'], true)) {
            $state = '';
        }

        $page = max(1, (int) ($_GET['page'] ?? 1));
        $perPage = 20;
        $totalNotifications = $this->notificationModel->countForUser($customerId, $state);
        $totalPages = max(1, (int) ceil($totalNotifications / $perPage));
        $page = min($page, $totalPages);
        $notifications = $this->notificationModel->getForUser(
            $customerId,
            $state,
            $perPage,
            ($page - 1) * $perPage
        );
        $unreadCount = $this->notificationModel->countUnreadByUser($customerId);

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

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

        $customerId = (int) $_SESSION['user']['id'];
        $notificationId = (int) ($_POST['notification_id'] ?? 0);
        $notification = $this->notificationModel->findOwnedByUser($notificationId, $customerId);

        if (!$notification) {
            $this->flashError('Thông báo không tồn tại.');
            $this->redirect('customer/notifications');
        }

        $this->notificationModel->markRead($notificationId, $customerId);
        $this->flashSuccess('Đã đánh dấu thông báo là đã đọc.');

        $link = (string) ($notification['link'] ?? '');
        if (preg_match('/^\?url=customer\/(?:order|booking)&id=[1-9][0-9]*$/', $link)) {
            header('Location: ' . BASE_URL . '/' . $link);
            exit;
        }

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

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

        $this->notificationModel->markAllRead((int) $_SESSION['user']['id']);
        $this->flashSuccess('Đã đánh dấu tất cả thông báo là đã đọc.');
        $this->redirect('customer/notifications');
    }
}
