<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    public function getNotifications(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Query notifikasi untuk admin
            // Admin melihat: notifikasi untuk role 'admin' (tanpa user_id) ATAU notifikasi untuk user_id mereka
            $query = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua admin (role = admin dan user_id = null)
                    $subQ->where('role', 'admin')
                  ->whereNull('user_id');
            })
                ->orWhere(function($subQ) use ($user) {
                    // Notifikasi spesifik untuk user ini
                    $subQ->where('user_id', $user->id);
                });
            })
            ->where('is_read', false)
            ->orderBy('created_at', 'desc');

            // Hitung total unread
            $totalUnread = (clone $query)->count();

            // 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(),
                'production' => (clone $query)->where('type', 'production')->count(),
            ];

            // Get recent notifications (limit 20)
            $recentNotifications = (clone $query)
                ->with(['order.product', 'inquiry.product', 'contact', 'production.product', 'production.order'])
                ->limit(20)
                ->get()
                ->map(function($notification) {
                    return $this->formatNotification($notification);
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'unread_counts' => [
                        'orders' => $unreadByType['order'],
                        'inquiries' => $unreadByType['inquiry'],
                        'contacts' => $unreadByType['contact'],
                        'productions' => $unreadByType['production'],
                        'total' => $totalUnread
                    ],
                    'recent_items' => [
                        'notifications' => $recentNotifications->values()->toArray()
                    ],
                    'last_updated' => now()->toISOString()
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('Error in NotificationController: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            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 && $notification->user_id !== Auth::id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak memiliki akses ke notifikasi ini'
                ], 403);
            }

            if ($notification->role && $notification->role !== Auth::user()->user_type) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak memiliki akses ke notifikasi ini'
                ], 403);
            }

            $notification->markAsRead();
            
            // Update is_read di tabel orders jika ada related_order_id
            if ($notification->related_order_id) {
                DB::table('orders')
                    ->where('id', $notification->related_order_id)
                    ->update(['is_read' => true]);
            }
            
            // Update is_read di tabel product_inquiries jika ada related_inquiry_id
            if ($notification->related_inquiry_id) {
                DB::table('product_inquiries')
                    ->where('id', $notification->related_inquiry_id)
                    ->update(['is_read' => true]);
            }
            
            // Update is_read di tabel contacts jika ada related_contact_id
            if ($notification->related_contact_id) {
                DB::table('contacts')
                    ->where('id', $notification->related_contact_id)
                    ->update(['is_read' => true]);
            }

            // Hitung ulang unread counts untuk update badge
            $user = Auth::user();
            $query = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    $subQ->where('role', 'admin')
                        ->whereNull('user_id');
                })
                ->orWhere(function($subQ) use ($user) {
                    $subQ->where('user_id', $user->id);
                });
            })
            ->where('is_read', false);
            
            $unreadByType = [
                'order' => (clone $query)->where('type', 'order')->count(),
                'inquiry' => (clone $query)->where('type', 'inquiry')->count(),
                'contact' => (clone $query)->where('type', 'contact')->count(),
                'production' => (clone $query)->where('type', 'production')->count(),
            ];

            return response()->json([
                'success' => true,
                'message' => 'Notifikasi ditandai sebagai dibaca',
                'data' => [
                    'unread_counts' => [
                        'orders' => $unreadByType['order'],
                        'inquiries' => $unreadByType['inquiry'],
                        'contacts' => $unreadByType['contact'],
                        'productions' => $unreadByType['production'],
                        'total' => (clone $query)->count()
                    ]
                ]
            ]);
        } 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 {
            $user = Auth::user();
            $type = $request->input('type', 'all');

            // Query yang lebih robust untuk memastikan semua notifikasi admin ter-cover
            // Termasuk notifikasi dengan role = 'admin' (dengan atau tanpa user_id)
            $query = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua admin (role = admin)
                    // Termasuk yang user_id null ATAU yang user_id tidak null (untuk backward compatibility)
                    $subQ->where('role', 'admin');
                })
                ->orWhere(function($subQ) use ($user) {
                    // Notifikasi spesifik untuk user ini (bisa dari role apapun)
                    $subQ->where('user_id', $user->id);
                });
            })
            ->where('is_read', false);

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

            // Hitung berapa banyak yang akan di-update untuk logging
            $count = $query->count();
            
            // Ambil notifikasi yang akan di-update SEBELUM di-update untuk mendapatkan related_order_id dan related_inquiry_id
            $notificationsToUpdate = $query->get(['id', 'type', 'role', 'user_id', 'is_read', 'related_order_id', 'related_inquiry_id']);
            \Log::info('Notifications to mark as read', [
                'count' => $count,
                'notifications' => $notificationsToUpdate->toArray()
            ]);
            
            // Kumpulkan order_id dan inquiry_id yang perlu di-update
            $orderIds = [];
            $inquiryIds = [];
            
            foreach ($notificationsToUpdate as $notification) {
                if ($notification->related_order_id) {
                    $orderIds[] = $notification->related_order_id;
                }
                if ($notification->related_inquiry_id) {
                    $inquiryIds[] = $notification->related_inquiry_id;
                }
            }
            
            // Update semua notifikasi yang sesuai
            $updated = $query->update([
                'is_read' => true, 
                'read_at' => now()
            ]);
            
            // Update is_read di tabel orders
            if (!empty($orderIds)) {
                $orderIds = array_unique($orderIds);
                DB::table('orders')
                    ->whereIn('id', $orderIds)
                    ->update(['is_read' => true]);
                \Log::info('Updated orders is_read', [
                    'order_ids' => $orderIds,
                    'count' => count($orderIds)
                ]);
            }
            
            // Update is_read di tabel product_inquiries
            if (!empty($inquiryIds)) {
                $inquiryIds = array_unique($inquiryIds);
                DB::table('product_inquiries')
                    ->whereIn('id', $inquiryIds)
                    ->update(['is_read' => true]);
                \Log::info('Updated inquiries is_read', [
                    'inquiry_ids' => $inquiryIds,
                    'count' => count($inquiryIds)
                ]);
            }

            \Log::info('Mark all notifications as read', [
                'user_id' => $user->id,
                'user_type' => $user->user_type,
                'type' => $type,
                'count_before' => $count,
                'updated' => $updated
            ]);

            // Verifikasi: Cek apakah masih ada notifikasi unread setelah update
            $remainingUnread = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    $subQ->where('role', 'admin');
                })
                ->orWhere(function($subQ) use ($user) {
                    $subQ->where('user_id', $user->id);
                });
            })
            ->where('is_read', false)
            ->count();

            if ($remainingUnread > 0) {
                \Log::warning('Still have unread notifications after mark all as read', [
                    'remaining_count' => $remainingUnread,
                    'user_id' => $user->id
                ]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Semua notifikasi telah ditandai sebagai dibaca',
                'data' => [
                    'updated_count' => $updated,
                    'remaining_unread' => $remainingUnread,
                    'unread_counts' => [
                        'total' => $remainingUnread,
                        'orders' => 0,
                        'inquiries' => 0,
                        'contacts' => 0,
                        'productions' => 0
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('Error in markAllAsRead: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            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,
            'related_production_id' => $notification->related_production_id,
            // Related data untuk kemudahan frontend
            '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,
            'production' => $notification->production ? [
                'id' => $notification->production->id,
                'order_id' => $notification->production->order_id,
                'product_title' => $notification->production->product?->product_title,
            ] : null,
        ];
    }
}
