<?php

namespace App\Http\Controllers\Teknisi;

use App\Http\Controllers\Controller;
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 {
            $teknisiId = Auth::id();
            
            // Query notifikasi untuk teknisi
            $query = Notification::where('user_id', $teknisiId)
                ->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 notifikasi dengan type 'inquiry' dan subtype 'inquiry_forwarded_teknisi'
            // Ini konsisten dengan cara admin menghitung (menggunakan notifikasi, bukan langsung dari product_inquiries)
            $unreadQuotations = (clone $query)
                ->where('type', 'inquiry')
                ->where('subtype', 'inquiry_forwarded_teknisi')
                ->count();

            // 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 Teknisi 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 !== Auth::id()) {
                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 (seperti admin)
            if ($notification->related_inquiry_id) {
                DB::table('product_inquiries')
                    ->where('id', $notification->related_inquiry_id)
                    ->update(['is_read' => true]);
            }

            // Hitung ulang unread counts untuk update badge
            $teknisiId = Auth::id();
            $query = Notification::where('user_id', $teknisiId)
                ->where('is_read', false);
            
            $unreadByType = [
                'inquiry' => (clone $query)->where('type', 'inquiry')->count(),
                'production' => (clone $query)->where('type', 'production')->count(),
            ];
            
            $unreadQuotations = (clone $query)
                ->where('type', 'inquiry')
                ->where('subtype', 'inquiry_forwarded_teknisi')
                ->count();

            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 {
            $teknisiId = Auth::id();
            $type = $request->input('type', 'all');

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

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

            // Ambil notifikasi yang akan di-update SEBELUM di-update untuk mendapatkan related_inquiry_id
            $notificationsToUpdate = $query->get(['id', 'type', 'user_id', 'is_read', 'related_inquiry_id']);
            
            // Kumpulkan inquiry_id yang perlu di-update
            $inquiryIds = [];
            foreach ($notificationsToUpdate as $notification) {
                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 product_inquiries (seperti admin)
            if (!empty($inquiryIds)) {
                $inquiryIds = array_unique($inquiryIds);
                DB::table('product_inquiries')
                    ->whereIn('id', $inquiryIds)
                    ->update(['is_read' => true]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Semua notifikasi telah ditandai sebagai dibaca'
            ]);
        } catch (\Exception $e) {
            \Log::error('Error in Teknisi 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,
                'order' => $notification->production->order ? [
                    'id' => $notification->production->order->id,
                    'customer_name' => $notification->production->order->customer_name,
                ] : null,
                'product' => $notification->production->product ? [
                    'id' => $notification->production->product->id,
                    'product_title' => $notification->production->product->product_title,
                ] : null,
            ] : null,
        ];
    }
}
