<?php

namespace App\Services;

use App\Models\AppNotification;
use App\Models\Assignment;
use App\Models\User;
use App\Models\UserPreference;
use App\Services\PushNotificationService;
use Carbon\Carbon;

class NotificationService
{
    /**
     * Create an in-app notification and send push notification.
     */
    public function createNotification(
        User $user,
        string $type,
        string $title,
        string $message,
        ?Assignment $assignment = null
    ): AppNotification {
        $notification = AppNotification::create([
            'user_id' => $user->id,
            'assignment_id' => $assignment?->id,
            'type' => $type,
            'title' => $title,
            'message' => $message,
            'sent_at' => now(),
        ]);

        // Send push notification to mobile devices
        if ($user->canReceiveAutomatedFeatures()) {
            try {
                $pushService = app(PushNotificationService::class);
                $pushService->sendToUser($user, $title, $message, [
                    'notification_id' => $notification->id,
                    'type' => $type,
                    'url' => $assignment ? route('assignments.show', $assignment) : route('notifications.index'),
                ]);
            } catch (\Exception $e) {
                // Log error but don't fail notification creation
                \Illuminate\Support\Facades\Log::error('Push notification failed', [
                    'error' => $e->getMessage(),
                    'user_id' => $user->id,
                ]);
            }
        }

        return $notification;
    }

    /**
     * Send study reminder notification.
     */
    public function sendStudyReminder(Assignment $assignment): void
    {
        if ($assignment->status === 'completed') {
            return;
        }

        $user = $assignment->user;
        
        // Check if user can receive automated notifications
        if (!$user->canReceiveAutomatedFeatures()) {
            return;
        }

        // Check quiet hours
        $preferences = $user->preferences;
        if ($preferences && $preferences->isQuietHours()) {
            return;
        }

        $plannedTime = $assignment->getPlannedStudyDateTime();
        
        $this->createNotification(
            $user,
            'study_reminder',
            'Study Session Reminder',
            "You have a planned study session for '{$assignment->assignment_title}' at {$plannedTime->format('g:i A')}.",
            $assignment
        );
    }

    /**
     * Send due date approaching notification.
     */
    public function sendDueDateApproaching(Assignment $assignment): void
    {
        if ($assignment->status === 'completed') {
            return;
        }

        $user = $assignment->user;
        
        if (!$user->canReceiveAutomatedFeatures()) {
            return;
        }

        $daysUntilDue = Carbon::now()->diffInDays($assignment->due_date, false);
        
        if ($daysUntilDue <= 1 && $daysUntilDue >= 0) {
            $this->createNotification(
                $user,
                'due_date_approaching',
                'Assignment Due Soon',
                "'{$assignment->assignment_title}' is due {$assignment->due_date->format('M d, Y')}.",
                $assignment
            );
        }
    }

    /**
     * Send overdue notification.
     */
    public function sendOverdueNotification(Assignment $assignment): void
    {
        if ($assignment->status === 'completed' || !$assignment->isOverdue()) {
            return;
        }

        $user = $assignment->user;
        
        if (!$user->canReceiveAutomatedFeatures()) {
            return;
        }

        $daysOverdue = Carbon::now()->diffInDays($assignment->due_date);
        
        $this->createNotification(
            $user,
            'overdue',
            'Assignment Overdue',
            "'{$assignment->assignment_title}' is {$daysOverdue} day(s) overdue. Please complete it as soon as possible.",
            $assignment
        );
    }

    /**
     * Send weekly risk warning.
     */
    public function sendWeeklyRiskWarning(User $user): void
    {
        if (!$user->canReceiveAutomatedFeatures()) {
            return;
        }

        $unfinishedAssignments = $user->assignments()
            ->pending()
            ->where('due_date', '>=', Carbon::now()->startOfWeek()->addWeek())
            ->where('due_date', '<=', Carbon::now()->startOfWeek()->addWeeks(2))
            ->count();

        if ($unfinishedAssignments > 0) {
            $this->createNotification(
                $user,
                'weekly_risk',
                'Weekly Risk Warning',
                "You have {$unfinishedAssignments} unfinished assignment(s) that may put you at risk of missing next week's deadlines.",
                null
            );
        }
    }

    /**
     * Send carry-over notification.
     */
    public function sendCarryOverNotification(Assignment $assignment): void
    {
        $user = $assignment->user;
        
        if (!$user->canReceiveAutomatedFeatures()) {
            return;
        }

        $this->createNotification(
            $user,
            'carry_over',
            'Assignment Carried Over',
            "'{$assignment->assignment_title}' has been automatically moved to tomorrow as your planned study session was missed.",
            $assignment
        );
    }
}
