<?php

namespace App\Http\Controllers\Supervisor;

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

class NotificationController extends Controller
{
    public function getNotifications(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Query notifikasi untuk supervisor
            // Supervisor melihat: notifikasi untuk role 'supervisor' (tanpa user_id) ATAU notifikasi untuk user_id mereka
            $query = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua supervisor (role = supervisor dan user_id = null)
                    $subQ->where('role', 'supervisor')
                  ->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 = [
                'inquiry' => (clone $query)->where('type', 'inquiry')->count(),
                'production' => (clone $query)->where('type', 'production')->count(),
            ];
            
            // Hitung unread quotations dari semua notifikasi dengan type 'inquiry'
            // Mengikuti cara admin menghitung (semua inquiry type, bukan hanya subtype tertentu)
            // Supervisor melihat semua inquiry yang perlu di-review
            $unreadQuotations = $unreadByType['inquiry'];

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

            return response()->json([
                'success' => true,
                'data' => [
                    'unread_counts' => [
                        'inquiries' => $unreadByType['inquiry'],
                        'productions' => $unreadByType['production'],
                        'quotations' => $unreadQuotations,
                        'total' => $totalUnread
                    ],
                    'recent_items' => [
                        'notifications' => $recentNotifications->values()->toArray()
                    ],
                    'last_updated' => now()->toISOString()
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('Error in Supervisor NotificationController: ' . $e->getMessage());
            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 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 productions jika ada related_production_id
            if ($notification->related_production_id) {
                // Tidak perlu update is_read di productions karena tidak ada field is_read
                // Tapi bisa update status jika diperlukan
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Notifikasi ditandai sebagai dibaca',
                'data' => [
                    'unread_counts' => [
                        'inquiries' => $unreadByType['inquiry'],
                        'productions' => $unreadByType['production'],
                        'quotations' => $unreadQuotations,
                        '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');

            // Gunakan query yang sama dengan getNotifications untuk konsistensi
            $query = Notification::where(function($q) use ($user) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua supervisor (role = supervisor dan user_id = null)
                    $subQ->where('role', 'supervisor')
                         ->whereNull('user_id');
                })
                ->orWhere(function($subQ) use ($user) {
                    // Notifikasi spesifik untuk user ini
                    $subQ->where('user_id', $user->id);
                });
            })
            ->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 Supervisor 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_inquiry_id' => $notification->related_inquiry_id,
            'related_production_id' => $notification->related_production_id,
            'inquiry' => $notification->inquiry ? [
                'id' => $notification->inquiry->id,
                'name' => $notification->inquiry->name,
                'product_title' => $notification->inquiry->product?->product_title,
            ] : null,
            'production' => $notification->production ? [
                'id' => $notification->production->id,
                'order_id' => $notification->production->order_id,
                'product_title' => $notification->production->product?->product_title,
            ] : null,
        ];
    }
}
