<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\AnalysisResult;

class NotificationsController extends Controller
{
    /**
     * Fetch recent notifications for authenticated user
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        
        // Generate notifications based on user's analysis results
        $notifications = [];
        
        // Get recent analysis results
        $recentAnalyses = AnalysisResult::where('user_id', $user->id)
            ->latest('created_at')
            ->limit(5)
            ->get();
        
        foreach ($recentAnalyses as $analysis) {
            $company = $analysis->company;
            $notifications[] = [
                'id' => 'analysis-' . $analysis->id,
                'type' => 'analysis',
                'title' => 'Analisis selesai',
                'message' => 'Analisis untuk ' . ($company->name ?? 'perusahaan') . ' telah selesai',
                'description' => $company->name ?? 'Perusahaan',
                'timestamp' => $analysis->created_at,
                'time_ago' => $this->timeAgo($analysis->created_at),
                'read' => false,
            ];
        }
        
        // Add subscription notifications
        $subscription = $user->currentSubscription();
        if ($subscription && $subscription->status === 'active') {
            $expiresIn = $subscription->expired_at->diffInDays(now());
            if ($expiresIn <= 7 && $expiresIn > 0) {
                $notifications[] = [
                    'id' => 'subscription-expiry',
                    'type' => 'subscription',
                    'title' => 'Langganan akan segera berakhir',
                    'message' => 'Langganan Anda akan berakhir dalam ' . $expiresIn . ' hari',
                    'description' => 'Perpanjang langganan',
                    'timestamp' => now(),
                    'time_ago' => 'Baru saja',
                    'read' => false,
                ];
            }
        }
        
        // Sort by timestamp
        usort($notifications, function ($a, $b) {
            return $b['timestamp']->getTimestamp() - $a['timestamp']->getTimestamp();
        });
        
        return response()->json([
            'success' => true,
            'notifications' => $notifications,
            'unread_count' => count(array_filter($notifications, fn($n) => !$n['read'])),
        ]);
    }
    
    /**
     * Mark notification as read
     */
    public function markAsRead(Request $request)
    {
        // In a real app, you'd store read status in database
        return response()->json(['success' => true, 'message' => 'Notifikasi ditandai sudah dibaca']);
    }
    
    /**
     * Helper function to convert timestamp to human readable format
     */
    private function timeAgo($date)
    {
        $seconds = time() - $date->getTimestamp();
        
        if ($seconds < 60) {
            return 'Baru saja';
        } elseif ($seconds < 3600) {
            $minutes = floor($seconds / 60);
            return $minutes . ' menit yang lalu';
        } elseif ($seconds < 86400) {
            $hours = floor($seconds / 3600);
            return $hours . ' jam yang lalu';
        } elseif ($seconds < 604800) {
            $days = floor($seconds / 86400);
            return $days . ' hari yang lalu';
        } else {
            return 'Lebih dari seminggu yang lalu';
        }
    }
}
