<?php

namespace Core\App\Controllers\Admin;

use Core\App\Models\AdminNotificationModel;
use PDO;

class NotificationController
{
    protected PDO $db;
    protected AdminNotificationModel $notifications;

    public function __construct()
    {
        $this->db = \db();
        $this->notifications = new AdminNotificationModel();
    }

    private function currentAdminId(): int
    {
        return (int)($_SESSION['admin_id'] ?? 0);
    }

    private function isManager(): bool
    {
        return in_array((string)($_SESSION['admin_role'] ?? ''), ['owner', 'manager'], true);
    }

    private function visibilitySql(): string
    {
        return $this->isManager()
            ? '(recipient_admin_id = :admin_id OR recipient_admin_id IS NULL)'
            : '(recipient_admin_id = :admin_id)';
    }

    private function scopedParams(): array
    {
        return [':admin_id' => $this->currentAdminId()];
    }

    /* =============================
       List Notifications (UNARCHIVED ONLY)
    ============================== */
    public function index()
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM admin_notifications
            WHERE archived = 0
              AND {$this->visibilitySql()}
            ORDER BY is_read ASC, created_at DESC
        ");
        $stmt->execute($this->scopedParams());

        $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        require ROOT_PATH . '/admin/templates/notifications/index.php';
    }

    /* =============================
       Mark One As Read
    ============================== */
    public function markRead(int $id)
    {
        $stmt = $this->db->prepare("
            UPDATE admin_notifications
            SET is_read = 1
            WHERE id = :id
              AND {$this->visibilitySql()}
        ");
        $stmt->execute(array_merge([':id' => $id], $this->scopedParams()));

        header('Location: /admin/notifications');
        exit;
    }

    /* =============================
       Mark All As Read
    ============================== */
    public function markAllRead()
    {
        $stmt = $this->db->prepare("
            UPDATE admin_notifications
            SET is_read = 1
            WHERE archived = 0
              AND {$this->visibilitySql()}
        ");
        $stmt->execute($this->scopedParams());

        header('Location: /admin/notifications');
        exit;
    }

    /* =============================
       Archive One
    ============================== */
    public function archive(int $id)
    {
        $stmt = $this->db->prepare("
            UPDATE admin_notifications
            SET archived = 1, is_read = 1
            WHERE id = :id
              AND {$this->visibilitySql()}
        ");
        $stmt->execute(array_merge([':id' => $id], $this->scopedParams()));

        header('Location: /admin/notifications');
        exit;
    }

    /* =============================
       Archive All
    ============================== */
    public function archiveAll()
    {
        $stmt = $this->db->prepare("
            UPDATE admin_notifications
            SET archived = 1, is_read = 1
            WHERE {$this->visibilitySql()}
        ");
        $stmt->execute($this->scopedParams());

        header('Location: /admin/notifications');
        exit;
    }

    /* =============================
       Resolve Notification Link
    ============================== */
public function resolveLink(array $n): string
{
    switch ($n['type']) {

        case 'review_pending':
        case 'product_review':
            return '/admin/reviews?open=' . (int)$n['reference_id'];

        case 'order_created':
        case 'order_assigned':
        case 'order_reassigned':
        case 'order_returned':
            return '/admin/orders/view/' . (int)$n['reference_id'];

        case 'team_message':
        case 'team_mention':
        case 'team_message_deleted':
            return '/admin/team/communication';

        case 'group_message':
        case 'team_group_mention':
        case 'meeting_started':
            return '/admin/team/meetings/room/' . (int)$n['reference_id'];

        default:
            return '/admin/notifications';
    }
}

public function unreadJson()
{
    $stmt = $this->db->prepare("
        SELECT id, title, type, reference_id, created_at
        FROM admin_notifications
        WHERE is_read = 0 AND archived = 0
          AND {$this->visibilitySql()}
        ORDER BY created_at DESC
        LIMIT 5
    ");
    $stmt->execute($this->scopedParams());

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    foreach ($rows as &$n) {
        $n['link'] = $this->resolveLink($n);
    }

    header('Content-Type: application/json');
    echo json_encode($rows);
    exit;
}

public function markReadFromDropdown(int $id)
{
    $stmt = $this->db->prepare("
        UPDATE admin_notifications
        SET is_read = 1
        WHERE id = :id
          AND {$this->visibilitySql()}
    ");
    $stmt->execute(array_merge([':id' => $id], $this->scopedParams()));

    header('Content-Type: application/json');
    echo json_encode(['success' => true]);
    exit;
}

public function unreadCount()
{
    $stmt = $this->db->prepare("
        SELECT COUNT(*) 
        FROM admin_notifications
        WHERE is_read = 0 AND archived = 0
          AND {$this->visibilitySql()}
    ");
    $stmt->execute($this->scopedParams());

    $count = (int) $stmt->fetchColumn();

    header('Content-Type: application/json');
    echo json_encode(['count' => $count]);
    exit;
}

/* =============================
   Show ONE Notification
============================= */
public function show(int $id)
{
    $stmt = $this->db->prepare("
        SELECT *
        FROM admin_notifications
        WHERE id = :id
          AND {$this->visibilitySql()}
        LIMIT 1
    ");
    $stmt->execute(array_merge([':id' => $id], $this->scopedParams()));

    $n = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$n) {
        http_response_code(404);
        return;
    }

    // mark read
    $this->db->prepare("
        UPDATE admin_notifications SET is_read = 1 WHERE id = :id AND {$this->visibilitySql()}
    ")->execute(array_merge([':id' => $id], $this->scopedParams()));

    echo '<script>window.location.href = "'
        . $this->resolveLink($n)
        . '";</script>';
    exit;
}

}
