<?php

namespace App\Http\Controllers;

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

class UserNotificationController extends Controller
{
    public function getNotifications(Request $request)
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                \Log::error('User Notification Error: User not authenticated');
                return response()->json([
                    'success' => false,
                    'message' => 'User tidak terautentikasi'
                ], 401);
            }
            
            \Log::info('User Notification Request', [
                'user_id' => $user->id,
                'user_email' => $user->email,
                'user_type' => $user->user_type
            ]);
            
            // Query notifikasi untuk user
            $query = Notification::where('user_id', $user->id)
                ->where('is_read', false)
                ->orderBy('created_at', 'desc');

            // Hitung total unread
            $totalUnread = (clone $query)->count();
            
            \Log::info('User Notification Query Result', [
                'user_id' => $user->id,
                'total_unread' => $totalUnread
            ]);

            // Hitung per type
            $unreadByType = [
                'order' => (clone $query)->where('type', 'order')->count(),
                'inquiry' => (clone $query)->where('type', 'inquiry')->count(),
                'contact' => (clone $query)->where('type', 'contact')->count(),
            ];

            // Get recent notifications (limit 20)
            $recentNotifications = (clone $query)
                ->with(['order.product', 'inquiry.product', 'contact'])
                ->limit(20)
                ->get()
                ->map(function($notification) {
                    return $this->formatNotification($notification);
                });
            
            \Log::info('User Notification Response', [
                'user_id' => $user->id,
                'total_unread' => $totalUnread,
                'recent_count' => $recentNotifications->count(),
                'unread_by_type' => $unreadByType
            ]);

            return response()->json([
                'success' => true,
                'data' => [
                    'unread_counts' => [
                        'orders' => $unreadByType['order'],
                        'inquiries' => $unreadByType['inquiry'],
                        'contacts' => $unreadByType['contact'],
                        'total' => $totalUnread
                    ],
                    'recent_items' => [
                        'notifications' => $recentNotifications->values()->toArray()
                    ],
                    'last_updated' => now()->toISOString()
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('User Notification Error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id()
            ]);
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil notifikasi: ' . $e->getMessage()
            ], 500);
        }
    }

    public function markAsRead(Request $request, $id)
    {
        try {
            $notification = Notification::findOrFail($id);
            
            // Pastikan user memiliki akses
            if ($notification->user_id !== Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak memiliki akses ke notifikasi ini'
                ], 403);
            }

            $notification->markAsRead();

            return response()->json([
                'success' => true,
                'message' => 'Notifikasi ditandai sebagai dibaca'
            ]);
        } catch (\Exception $e) {
            \Log::error('Error marking notification as read: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal update status: ' . $e->getMessage()
            ], 500);
        }
    }

    public function markAllAsRead(Request $request)
    {
        try {
            $userId = Auth::id();
            $type = $request->input('type', 'all');

            $query = Notification::where('user_id', $userId)
                ->where('is_read', false);

            if ($type !== 'all') {
                $query->where('type', $type);
            }

            $query->update(['is_read' => true, 'read_at' => now()]);

            return response()->json([
                'success' => true,
                'message' => 'Semua notifikasi telah ditandai sebagai dibaca'
            ]);
        } catch (\Exception $e) {
            \Log::error('Error in User markAllAsRead: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal update status: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Format notification untuk response
     */
    protected function formatNotification(Notification $notification)
    {
        $data = $notification->data ?? [];
        
        return [
            'id' => $notification->id,
            'type' => $notification->type,
            'subtype' => $notification->subtype,
            'title' => $notification->title,
            'message' => $notification->message,
            'data' => $data,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at->toISOString(),
            'read_at' => $notification->read_at?->toISOString(),
            'related_order_id' => $notification->related_order_id,
            'related_inquiry_id' => $notification->related_inquiry_id,
            'related_contact_id' => $notification->related_contact_id,
            'order' => $notification->order ? [
                'id' => $notification->order->id,
                'customer_name' => $notification->order->customer_name,
                'product_title' => $notification->order->product?->product_title,
            ] : null,
            'inquiry' => $notification->inquiry ? [
                'id' => $notification->inquiry->id,
                'name' => $notification->inquiry->name,
                'product_title' => $notification->inquiry->product?->product_title,
            ] : null,
            'contact' => $notification->contact ? [
                'id' => $notification->contact->id,
                'nama' => $notification->contact->nama,
            ] : null,
        ];
    }
}
