const express = require('express');
const router = express.Router();
const mongoose = require('mongoose'); // ✅ FIX: Required for ObjectId.isValid() in /orders/:id
const User = require('../models/User');
const Order = require('../models/Order');
const Settings = require('../models/Settings');
const { protect, adminOnly } = require('../middleware/authMiddleware');
const { normalizePhone } = require('../utils/phoneNormalizer');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const rateLimit = require('express-rate-limit');
const logger = require('../utils/logger');

// تم استيراد adminOnly من الميدل وير

// ==========================================
// 🛡️ Admin strict login route
// ==========================================
const adminLoginLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5,
    message: { message: 'محاولات دخول كثيرة للوحة التحكم. يرجى الانتظار 15 دقيقة.' },
    standardHeaders: true,
    legacyHeaders: false,
    validate: { xForwardedForHeader: false, trustProxy: false, ip: false }
});

router.post('/login', adminLoginLimiter, async (req, res) => {
    try {
        const { email, password } = req.body;
        if (!email || !password) return res.status(400).json({ message: 'يرجى إدخال البيانات' });

        const user = await User.findOne({ email: email.toLowerCase().trim() });
        if (!user || user.role !== 'admin') {
            return res.status(403).json({ message: 'بيانات الدخول غير صحيحة أو لست مسؤولاً' });
        }

        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) return res.status(400).json({ message: 'بيانات الدخول غير صحيحة' });

        const token = jwt.sign(
            { userId: user._id, role: user.role },
            process.env.JWT_SECRET,
            { expiresIn: '7d' }
        );

        res.json({
            token,
            user: { _id: user._id, name: user.name, role: user.role, email: user.email }
        });
    } catch (err) {
        logger.error('Admin Login Error:', err.message);
        res.status(500).json({ message: 'حدث خطأ في السيرفر أثناء الدخول' });
    }
});

// =========================================================
// 📊 الجزء الأول: الإحصائيات والداشبورد (Dashboard)
// =========================================================

// @route   GET /api/admin/dashboard
// @desc    جلب إحصائيات النظام الشاملة وآخر 5 طلبات
// Simple in-memory cache to avoid repeated heavy dashboard queries
let _dashboardCache = null;
let _dashboardCacheTime = 0;
const DASHBOARD_CACHE_TTL = 30000; // 30 seconds

router.get('/dashboard', protect, adminOnly, async (req, res) => {
    try {
        const now = Date.now();
        if (_dashboardCache && (now - _dashboardCacheTime) < DASHBOARD_CACHE_TTL) {
            return res.json(_dashboardCache);
        }

        // تشغيل جميع الاستعلامات في وقت واحد لتسريع التحميل
        const [
            captainsCount,
            customersCount,
            ordersCount,
            revenueResult,
            debtSummary,
            ordersByStatusResult,
            recentOrders
        ] = await Promise.all([
            User.countDocuments({ role: 'captain' }),
            User.countDocuments({ role: { $in: ['client', 'customer'] } }),
            Order.countDocuments({}),
            Order.aggregate([
                { $match: { status: 'delivered' } },
                { $group: { _id: null, total: { $sum: "$appFee" } } }
            ]),
            require('../models/DebtAdjustment').aggregate([
                { $group: { _id: '$mode', total: { $sum: '$amount' } } }
            ]),
            Order.aggregate([
                { $group: { _id: "$status", count: { $sum: 1 } } }
            ]),
            Order.find()
                .select('status price pickup dropoff createdAt client captain')
                .populate('client', 'name phone')
                .populate('captain', 'name phone')
                .sort({ createdAt: -1 })
                .limit(5)
                .lean()
        ]);

        const ordersRevenue = revenueResult.length > 0 ? revenueResult[0].total : 0;

        let debtAdded = 0;
        let debtForgiven = 0;
        debtSummary.forEach(row => {
            if (row._id === 'add') debtAdded = row.total;
            else debtForgiven += row.total;
        });

        const totalRevenue = ordersRevenue + debtAdded - debtForgiven;

        const ordersByStatus = {
            pending: 0, scheduled: 0, accepted: 0,
            picked_up: 0, delivered: 0, cancelled: 0
        };
        ordersByStatusResult.forEach(item => {
            if (ordersByStatus.hasOwnProperty(item._id)) {
                ordersByStatus[item._id] = item.count;
            }
        });

        const responseData = {
            stats: {
                captains: captainsCount,
                customers: customersCount,
                orders: ordersCount,
                revenue: totalRevenue,
                revenueBreakdown: { ordersRevenue, debtAdded, debtForgiven, netRevenue: totalRevenue }
            },
            ordersByStatus,
            recentOrders
        };

        _dashboardCache = responseData;
        _dashboardCacheTime = now;

        res.json(responseData);

    } catch (error) {
        logger.error("Dashboard Error:", error);
        res.status(500).json({ message: 'حدث خطأ في السيرفر' });
    }
});

// @route   GET /api/admin/user/:id
// @desc    جلب بيانات مستخدم محدد
router.get('/user/:id', protect, adminOnly, async (req, res) => {
    try {
        const user = await User.findById(req.params.id).select('-password');
        if (!user) {
            return res.status(404).json({ message: 'المستخدم غير موجود' });
        }
        res.json(user);
    } catch (error) {
        logger.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

// =========================================================
// 👥 الجزء الثاني: إدارة المستخدمين
// =========================================================

// @route   GET /api/admin/users
// @desc    جلب جميع المستخدمين
router.get('/users', protect, adminOnly, async (req, res) => {
    try {
        const users = await User.find().select('-password').sort({ createdAt: -1 });
        res.json(users);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   GET /api/admin/captains
// @desc    جلب الكباتن فقط
router.get('/captains', protect, adminOnly, async (req, res) => {
    try {
        const captains = await User.find({ role: 'captain' }).select('-password');
        res.json(captains);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   PUT /api/admin/user/:id/status
// @desc    تفعيل أو تعطيل حساب مستخدم
router.put('/user/:id/status', protect, adminOnly, async (req, res) => {
    try {
        // حماية: منع الأدمن من تعطيل نفسه
        if (req.user._id.toString() === req.params.id) {
            return res.status(400).json({ message: 'لا يمكنك تعطيل حسابك الشخصي!' });
        }

        const user = await User.findById(req.params.id);

        if (!user) {
            return res.status(404).json({ message: 'المستخدم غير موجود' });
        }

        user.isActive = !user.isActive; // عكس الحالة الحالية
        await user.save();

        res.json({
            message: `تم ${user.isActive ? 'تفعيل' : 'تعطيل'} الحساب بنجاح`,
            isActive: user.isActive,
        });

    } catch (error) {
        logger.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

// =========================================================
// 📦 الجزء الثالث: الطلبات (سجل الطلبات الكامل)
// =========================================================

// @route   GET /api/admin/orders/live
// @desc    جلب الطلبات النشطة فقط (لتخفيف الضغط وتحسين السرعة)
router.get('/orders/live', protect, adminOnly, async (req, res) => {
    try {
        const liveStatuses = ['pending', 'scheduled', 'accepted', 'picked_up'];
        const orders = await Order.find({ status: { $in: liveStatuses } })
            .select('status price pickup dropoff createdAt client captain type')
            .populate('client', 'name phone')
            .populate('captain', 'name phone')
            .sort({ createdAt: -1 })
            .limit(50)
            .lean();
        res.json(orders);
    } catch (error) {
        logger.error("Live Orders Error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   GET /api/admin/orders/:id
// @desc    جلب طلب واحد بالتفصيل (لصفحة تفاصيل الطلب)
router.get('/orders/:id', protect, adminOnly, async (req, res) => {
    try {
        // نتحقق من أن الـ id أوبجكت صحيح لتفادي كراش
        if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
            return res.status(404).json({ message: 'Not found' });
        }
        const order = await Order.findById(req.params.id)
            .populate('client', 'name phone')
            .populate('captain', 'name phone');
        if (!order) return res.status(404).json({ message: 'Not found' });
        res.json(order);
    } catch (error) {
        logger.error("Order Details Error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   GET /api/admin/orders
// @desc    جلب جميع الطلبات (لصفحة السجل الكامل)
router.get('/orders', protect, adminOnly, async (req, res) => {
    try {
        const orders = await Order.find()
            .select('status price pickup dropoff createdAt client captain type totalAmount')
            .populate('client', 'name phone')
            .populate('captain', 'name phone')
            .sort({ createdAt: -1 })
            .limit(200)
            .lean();

        res.json(orders);
    } catch (error) {
        logger.error("Orders Error:", error);
        res.status(500).json({ message: 'Server error' });
    }
});

// =========================================================
// 🚩 الجزء الرابع: الشكاوى
// =========================================================

// @route   GET /api/admin/complaints
// @desc    جلب الطلبات التي بها شكاوى
router.get('/complaints', protect, adminOnly, async (req, res) => {
    try {
        // البحث عن أي طلب يحتوي على حالة شكوى لا تساوي 'none'
        const orders = await Order.find({
            'complaint.status': { $exists: true, $ne: 'none' }
        })
            .populate('client', 'name phone')
            .populate('captain', 'name phone')
            .sort({ 'complaint.createdAt': -1 });

        res.json(orders);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   PUT /api/admin/complaints/:id/resolve
// @desc    حل الشكوى
router.put('/complaints/:id/resolve', protect, adminOnly, async (req, res) => {
    try {
        const order = await Order.findById(req.params.id);
        if (!order) return res.status(404).json({ message: 'الطلب غير موجود' });

        if (!order.complaint) {
            order.complaint = {}; // إنشاء كائن الشكوى إذا لم يكن موجوداً
        }

        order.complaint.status = 'resolved';
        order.complaint.resolvedAt = Date.now();

        await order.save();
        res.json({ message: 'تم حل الشكوى بنجاح', order });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});
// =========================================================
// 🆕 إضافة كابتن جديد (بواسطة الأدمن فقط)
// =========================================================
// @route   POST /api/admin/create-captain
router.post('/create-captain', protect, adminOnly, async (req, res) => {
    try {
        const { name, email, phone, password, vehicleType } = req.body;

        // تنسيق رقم الهاتف
        const normalizedPhone = normalizePhone(phone);
        logger.info(`📞 Create Captain - Original: ${phone}, Normalized: ${normalizedPhone}`);

        // التحقق من وجود المستخدم مسبقاً
        const userExists = await User.findOne({ $or: [{ email }, { phone: normalizedPhone }] });
        if (userExists) {
            return res.status(400).json({ message: 'المستخدم موجود بالفعل (البريد أو الهاتف مسجل مسبقاً)' });
        }

        // إنشاء المستخدم
        const user = await User.create({
            name,
            email,
            phone: normalizedPhone, // استخدام الرقم المنسق
            password, // يفترض أن الموديل يقوم بتشفير كلمة المرور تلقائياً
            role: 'captain',
            vehicleType, // تأكد أن هذا الحقل موجود في المودل الخاص بك، أو احذفه إذا لم يكن موجوداً
            isActive: true,
            isVerified: true,
            approvalStatus: 'approved' // ✅ Admin-created captains are auto-approved
        });

        if (user) {
            res.status(201).json({
                _id: user._id,
                name: user.name,
                email: user.email,
                role: user.role,
                message: "تم إنشاء حساب الكابتن بنجاح"
            });
        } else {
            res.status(400).json({ message: 'بيانات المستخدم غير صحيحة' });
        }

    } catch (error) {
        logger.error("Create Captain Error:", error);
        res.status(500).json({ message: 'حدث خطأ في السيرفر' });
    }
});
// @route   PUT /api/admin/orders/:id/cancel-force
router.put('/orders/:id/cancel-force', protect, adminOnly, async (req, res) => {
    try {
        const order = await Order.findById(req.params.id);
        if (!order) return res.status(404).json({ message: 'الطلب غير موجود' });

        if (order.status === 'delivered') {
            return res.status(400).json({ message: 'لا يمكن إلغاء طلب تم توصيله بالفعل' });
        }
        if (order.status === 'cancelled') {
            return res.status(400).json({ message: 'الطلب ملغي مسبقاً' });
        }

        // 🚀 FIX 4: Send all missing notifications on admin force-cancel
        const io = req.app.get('io');
        const { sendNotification } = require('../utils/notificationHelper');
        
        order.status = 'cancelled';
        
        // Notify negotiating captains — collect capIds first, emit AFTER save
        const pendingCapIds = [];
        if (order.negotiations && order.negotiations.length > 0) {
            for (let i = 0; i < order.negotiations.length; i++) {
                if (order.negotiations[i].status === 'pending') {
                    order.negotiations[i].status = 'rejected';
                    const capId = order.negotiations[i].captainId;
                    if (capId) pendingCapIds.push(capId);
                }
            }
        }
        await order.save();

        // BUG #18 FIX: All socket emits and notifications are now AFTER save
        for (const capId of pendingCapIds) {
            if (io) {
                io.to(capId.toString()).emit('negotiation_resolved', {
                    orderId: order._id,
                    result: 'order_taken'
                });
            }
        }

        // Notify client
        if (order.client) {
            if (io) io.to(order.client.toString()).emit('order_status_updated', { orderId: order._id, status: 'cancelled' });
            await sendNotification(req.app, {
                userId: order.client,
                title: '⚠️ تم إلغاء الطلب إدارياً',
                message: `قامت الإدارة بإلغاء طلبك رقم ${order._id.toString().slice(-6)}.`,
                type: 'order_update',
                relatedId: order._id
            });
        }
        
        // Notify assigned captain if any
        if (order.captain) {
            if (io) io.to(order.captain.toString()).emit('order_status_updated', { orderId: order._id, status: 'cancelled' });
            await sendNotification(req.app, {
                userId: order.captain,
                title: '⚠️ تم إلغاء الطلب إدارياً',
                message: `قامت الإدارة بإلغاء الطلب الذي تم تعيينه لك.`,
                type: 'order_update',
                relatedId: order._id
            });
        }
        
        // Broadcast to admin panel
        if (io) io.emit('admin_order_update', { orderId: order._id, status: 'cancelled' });

        res.json({ message: 'تم إلغاء الطلب إجبارياً بواسطة الإدارة وإشعار الأطراف', order });
    } catch (error) {
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 🔄 تبديل الكابتن على طلب نشط (Admin Reassign)
// @route   PUT /api/admin/orders/:id/reassign-captain
// body: { newCaptainId: '...' }
// =========================================================
router.put('/orders/:id/reassign-captain', protect, adminOnly, async (req, res) => {
    try {
        const { sendNotification } = require('../utils/notificationHelper');
        const { newCaptainId } = req.body;
        if (!newCaptainId) return res.status(400).json({ message: 'يرجى تحديد الكابتن الجديد' });

        const order = await Order.findById(req.params.id).populate('captain', 'name');
        if (!order) return res.status(404).json({ message: 'الطلب غير موجود' });

        if (!['accepted', 'picked_up'].includes(order.status)) {
            return res.status(400).json({ message: 'لا يمكن تبديل الكابتن إلا في طلبات نشطة (مقبول / قيد التوصيل)' });
        }

        const newCaptain = await User.findById(newCaptainId).select('name phone role is_blocked');
        if (!newCaptain || newCaptain.role !== 'captain') {
            return res.status(404).json({ message: 'الكابتن الجديد غير موجود' });
        }

        // 🚀 FIX 5: Prevent reassigning to a blocked captain
        if (newCaptain.is_blocked) {
            return res.status(400).json({ message: 'لا يمكن إسناد الطلب لهذا الكابتن لأن حسابه محظور (تجاوز الحد الائتماني)' });
        }

        const oldCaptainId = order.captain?._id;
        const oldCaptainName = order.captain?.name || 'الكابتن السابق';

        // Reassign
        order.captain = newCaptainId;
        await order.save();

        const io = req.app.get('io');

        // Notify OLD captain
        if (oldCaptainId) {
            if (io) {
                io.to(oldCaptainId.toString()).emit('order_status_updated', {
                    orderId: order._id,
                    status: 'reassigned'
                });
            }
            await sendNotification(req.app, {
                userId: oldCaptainId,
                title: '⚠️ تم نقل الطلب',
                message: `قامت الإدارة بنقل الطلب #${order._id.toString().slice(-6)} إلى كابتن آخر.`,
                type: 'order_update',
                relatedId: order._id
            });
        }

        // Notify NEW captain
        if (io) {
            io.to(newCaptainId.toString()).emit('order_reassigned', {
                orderId: order._id,
                message: 'تم تعيينك على طلب من قِبل الإدارة'
            });
        }
        await sendNotification(req.app, {
            userId: newCaptainId,
            title: '🚀 تم تعيينك على طلب',
            message: `قامت الإدارة بتعيينك على الطلب #${order._id.toString().slice(-6)}.`,
            type: 'order_accepted',
            relatedId: order._id
        });

        // Notify client
        if (io) {
            io.to(order.client.toString()).emit('new_notification', {
                title: '🔄 تم تغيير الكابتن',
                message: `قامت الإدارة بتعيين الكابتن ${newCaptain.name} على طلبك.`,
                type: 'order_update'
            });
        }

        res.json({ message: `تم تحويل الطلب من ${oldCaptainName} إلى ${newCaptain.name} بنجاح`, order });
    } catch (error) {
        logger.error({ err: error }, 'Reassign Captain Error');
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 💳 إدارة مديونية كابتن (تصفير / نقص جزء / إضافة دين) — Admin Debt Adjust
// @route   PUT /api/admin/captains/:id/adjust-debt
// body: { mode: 'zero' | 'partial' | 'add', amount?: number, note?: string }
// =========================================================
// mode=zero   => reset balance to 0
// mode=partial => reduce debt by `amount` (bring closer to 0)
// mode=add     => add debt by `amount` (push balance further negative)
router.put('/captains/:id/adjust-debt', protect, adminOnly, async (req, res) => {
    try {
        const { sendNotification } = require('../utils/notificationHelper');
        const { mode, amount, note } = req.body;

        if (!['zero', 'partial', 'add'].includes(mode)) {
            return res.status(400).json({ message: 'mode يجب أن يكون zero أو partial أو add' });
        }

        const captain = await User.findById(req.params.id);
        if (!captain || captain.role !== 'captain') {
            return res.status(404).json({ message: 'الكابتن غير موجود' });
        }

        const previousBalance = captain.wallet_balance ?? 0;

        // Guard: zero/partial only work when captain has debt
        if (mode !== 'add' && previousBalance >= 0) {
            return res.status(400).json({ message: 'هذا الكابتن ليس لديه مديونية' });
        }

        if ((mode === 'partial' || mode === 'add') && (!amount || amount <= 0)) {
            return res.status(400).json({ message: 'يرجى إدخال مبلغ صحيح أكبر من صفر' });
        }
        if (amount > 1000000) {
            return res.status(400).json({ message: 'المبلغ المدخل مبالغ فيه (الحد الأقصى مليون)' });
        }

        let updateQuery = {};
        let adjustedAmount = 0;
        let expectedNewBalance = 0; // Just for logging

        if (mode === 'zero') {
            updateQuery = { $set: { wallet_balance: 0 } };
            adjustedAmount = Math.abs(previousBalance);
        } else if (mode === 'partial') {
            // BUG #9 FIX: Use aggregation pipeline update to atomically cap at 0 in one operation.
            // The old { $inc, $min } was two separate ops and could overshoot in a race condition.
            updateQuery = [{ $set: { wallet_balance: { $min: [0, { $add: ['$wallet_balance', amount] }] } } }];
            adjustedAmount = amount;
        } else { // add
            updateQuery = { $inc: { wallet_balance: -amount } };
            adjustedAmount = amount;
        }

        // BUG #9 FIX: Aggregation pipeline update is now used for partial mode (atomic cap at 0)
        let updatedCaptain = await User.findByIdAndUpdate(req.params.id, updateQuery, { new: true });

        // Auto-block/unblock logic (لا تؤثر على الرصيد — آمن من race condition)
        let changed = false;
        const creditLimit = updatedCaptain.credit_limit ?? -5000;
        // Auto-unblock if balance recovered above credit limit
        if (updatedCaptain.is_blocked && updatedCaptain.wallet_balance > creditLimit) {
            updatedCaptain.is_blocked = false;
            changed = true;
        }
        // Auto-block if new debt crosses the credit limit
        if (!updatedCaptain.is_blocked && updatedCaptain.wallet_balance <= creditLimit) {
            updatedCaptain.is_blocked = true;
            changed = true;
        }

        if (changed) {
            await updatedCaptain.save();
        }
        
        const newBalance = updatedCaptain.wallet_balance;

        // 📒 سجّل التعديل في DebtAdjustment للتقارير المالية
        try {
            const DebtAdjustment = require('../models/DebtAdjustment');
            await DebtAdjustment.create({
                captain: captain._id,
                admin: req.user._id,
                mode,
                amount: adjustedAmount,
                previousBalance,
                newBalance,
                note: note || ''
            });
        } catch (logErr) {
            logger.warn({ err: logErr }, 'Failed to record DebtAdjustment audit entry');
            // لا نُفشل الطلب لو فشل التسجيل — التعديل المالي تم بنجاح
        }

        logger.info(`[Admin Debt Adjust] Captain: ${captain.name} | ${previousBalance} → ${newBalance} | Mode: ${mode} | Amount: ${adjustedAmount} | Note: ${note || '—'}`);

        // Notify captain
        let notifMsg;
        if (mode === 'zero') {
            notifMsg = `قامت الإدارة بتصفير مديونيتك بالكامل. رصيدك الحالي: 0 ج.س`;
        } else if (mode === 'partial') {
            notifMsg = `قامت الإدارة بتخفيض مديونيتك بمقدار ${adjustedAmount.toFixed(0)} ج.س. رصيدك الحالي: ${newBalance.toFixed(0)} ج.س`;
        } else {
            notifMsg = `قامت الإدارة بإضافة مديونية بمقدار ${adjustedAmount.toFixed(0)} ج.س. رصيدك الحالي: ${newBalance.toFixed(0)} ج.س${note ? ' — ' + note : ''}`;
        }

        await sendNotification(req.app, {
            userId: captain._id,
            title: mode === 'add' ? '⚠️ تم إضافة مديونية' : '💳 تم تعديل رصيدك',
            message: notifMsg,
            type: 'order_update',
            relatedId: captain._id
        });

        let responseMsg;
        if (mode === 'zero')    responseMsg = 'تم تصفير المديونية بنجاح';
        else if (mode === 'partial') responseMsg = `تم خصم ${adjustedAmount.toFixed(0)} ج.س من المديونية`;
        else                    responseMsg = `تم إضافة مديونية ${adjustedAmount.toFixed(0)} ج.س للكابتن${captain.is_blocked ? ' (تم حجب الحساب تلقائياً)' : ''}`;

        res.json({
            message: responseMsg,
            previousBalance,
            newBalance: updatedCaptain.wallet_balance,
            adjustedAmount,
            isUnblocked: mode !== 'add' && !updatedCaptain.is_blocked,
            isBlocked: updatedCaptain.is_blocked
        });
    } catch (error) {
        logger.error({ err: error }, 'Adjust Debt Error');
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 📒 سجل تعديلات المديونية — للتقارير المالية
// @route   GET /api/admin/debt-adjustments
// query: ?from=YYYY-MM-DD&to=YYYY-MM-DD&captainId=...&mode=add|zero|partial&limit=100
// =========================================================
router.get('/debt-adjustments', protect, adminOnly, async (req, res) => {
    try {
        const DebtAdjustment = require('../models/DebtAdjustment');
        const { from, to, captainId, mode, limit } = req.query;

        const filter = {};
        if (from || to) {
            filter.createdAt = {};
            if (from) filter.createdAt.$gte = new Date(from);
            if (to) filter.createdAt.$lte = new Date(to);
        }
        if (captainId) filter.captain = captainId;
        if (mode && ['add', 'zero', 'partial'].includes(mode)) filter.mode = mode;

        const max = Math.min(parseInt(limit, 10) || 100, 500);

        const [entries, summary] = await Promise.all([
            DebtAdjustment.find(filter)
                .populate('captain', 'name phone')
                .populate('admin', 'name')
                .sort({ createdAt: -1 })
                .limit(max),
            DebtAdjustment.aggregate([
                { $match: filter },
                { $group: { _id: '$mode', total: { $sum: '$amount' }, count: { $sum: 1 } } }
            ])
        ]);

        let debtAdded = 0, debtForgiven = 0, addCount = 0, zeroCount = 0, partialCount = 0;
        summary.forEach(row => {
            if (row._id === 'add')     { debtAdded = row.total; addCount = row.count; }
            else if (row._id === 'zero')    { debtForgiven += row.total; zeroCount = row.count; }
            else if (row._id === 'partial') { debtForgiven += row.total; partialCount = row.count; }
        });

        res.json({
            entries,
            summary: {
                debtAdded,
                debtForgiven,
                netImpact: debtAdded - debtForgiven,
                counts: { add: addCount, zero: zeroCount, partial: partialCount, total: addCount + zeroCount + partialCount }
            }
        });
    } catch (error) {
        logger.error({ err: error }, 'Debt Adjustments Report Error');
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 🚀 إدارة طلبات الكباتن المعلقة (Captain Approval)
// =========================================================

// @route   GET /api/admin/pending-captains
router.get('/pending-captains', protect, adminOnly, async (req, res) => {
    try {
        const captains = await User.find({ role: 'captain', approvalStatus: 'pending' })
            .select('-password')
            .sort({ createdAt: -1 });
        res.json(captains);
    } catch (error) {
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/approve-captain/:id
router.put('/approve-captain/:id', protect, adminOnly, async (req, res) => {
    try {
        const captain = await User.findById(req.params.id);
        if (!captain) return res.status(404).json({ message: 'الكابتن غير موجود' });
        if (captain.role !== 'captain') return res.status(400).json({ message: 'هذا المستخدم ليس كابتن' });

        captain.approvalStatus = 'approved';
        captain.isVerified = true;
        captain.isActive = true;
        await captain.save();

        // Notify captain
        const { sendNotification } = require('../utils/notificationHelper');
        await sendNotification(req.app, {
            userId: captain._id,
            title: '🎉 تمت الموافقة على طلبك!',
            message: 'تم قبولك ككابتن في وصل-لي. يمكنك الآن تسجيل الدخول والبدء في استقبال الطلبات!',
            type: 'system',
            relatedId: captain._id
        });

        res.json({ message: 'تمت الموافقة على الكابتن بنجاح', captain });
    } catch (error) {
        logger.error('Approve Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/reject-captain/:id
router.put('/reject-captain/:id', protect, adminOnly, async (req, res) => {
    try {
        const { reason } = req.body;
        const captain = await User.findById(req.params.id);
        if (!captain) return res.status(404).json({ message: 'الكابتن غير موجود' });
        if (captain.role !== 'captain') return res.status(400).json({ message: 'هذا المستخدم ليس كابتن' });

        captain.approvalStatus = 'rejected';
        captain.rejectionReason = reason || 'لم يتم تحديد السبب';
        captain.isActive = false;
        await captain.save();

        const { sendNotification } = require('../utils/notificationHelper');
        await sendNotification(req.app, {
            userId: captain._id,
            title: '❌ تم رفض طلبك',
            message: `سبب الرفض: ${captain.rejectionReason}`,
            type: 'system',
            relatedId: captain._id
        });

        res.json({ message: 'تم رفض طلب الكابتن', captain });
    } catch (error) {
        logger.error('Reject Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// ⚙️ الجزء الخامس: الإعدادات (Settings)
// =========================================================

// @route   GET /api/admin/settings
// @desc    جلب الإعدادات (للأدمن فقط)
router.get('/settings', protect, adminOnly, async (req, res) => {
    try {
        // ✅ Always sort by updatedAt:-1 to read the SAME doc that PUT /settings updates
        const settings = await Settings.findOne().sort({ updatedAt: -1 }).lean();
        if (!settings) {
            const newSettings = await Settings.create({});
            return res.json(newSettings.toObject());
        }
        res.json(settings);
    } catch (error) {
        logger.error('Settings Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   GET /api/admin/debug-settings
// @desc    تشخيص — يعرض كل وثائق Settings في DB (للأدمن فقط)
router.get('/debug-settings', protect, adminOnly, async (req, res) => {
    try {
        const mongoose = require('mongoose');
        const allDocs = await mongoose.connection.db
            .collection('settings')
            .find({})
            .toArray();
        res.json({
            count: allDocs.length,
            docs: allDocs.map(d => ({
                _id: d._id,
                defaultCreditLimit: d.defaultCreditLimit,
                bankName: d.bankName,
                bankAccountName: d.bankAccountName,
                bankAccountNumber: d.bankAccountNumber,
                commissionRate: d.commissionRate,
                updatedAt: d.updatedAt
            }))
        });
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

// @route   GET /api/admin/pricing
// @desc    جلب إعدادات التسعير فقط (متاح لجميع المستخدمين المسجلين)
router.get('/pricing', protect, async (req, res) => {
    try {
        const settings = await Settings.getSettings();
        // نُعيد فقط حقول التسعير — لا بيانات حساسة
        res.json({
            baseFare: settings.baseFare || 1000,
            shortDistance: settings.shortDistance || 1000,
            mediumDistance: settings.mediumDistance || 3000,
            longDistance: settings.longDistance || 6000,
            costPerKm: settings.costPerKm || 200,
            costPerMinute: settings.costPerMinute || 0,
            commissionRate: settings.commissionRate ?? 0.15, // ✅ نسبة العمولة الرسمية
        });
    } catch (error) {
        logger.error("Pricing Error:", error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/settings
// @desc    تحديث الإعدادات المالية — atomic upsert
router.put('/settings', protect, adminOnly, async (req, res) => {
    try {
        const allowedFields = [
            'baseFare', 'costPerKm', 'costPerMinute',
            'commissionRate', 'adminPhone',
            'defaultCreditLimit',
            'bankName', 'bankAccountName', 'bankAccountNumber',
            'appVersion', 'minVersion', 'playStoreLink', 'forceUpdate'
        ];

        const updates = { updatedBy: req.user._id };
        for (const field of allowedFields) {
            if (req.body[field] !== undefined) {
                updates[field] = req.body[field];
            }
        }

        const numericFields = ['baseFare', 'costPerKm', 'costPerMinute', 'commissionRate', 'defaultCreditLimit'];
        for (const field of numericFields) {
            if (updates[field] !== undefined) {
                const val = parseFloat(updates[field]);
                if (isNaN(val) || val < 0) return res.status(400).json({ message: `القيمة المدخلة في ${field} غير صالحة` });
                if (field !== 'commissionRate' && val > 1000000) return res.status(400).json({ message: `القيمة المدخلة في ${field} مبالغ فيها` });
                if (field === 'commissionRate' && val > 1) return res.status(400).json({ message: `نسبة العمولة يجب أن تكون بين 0 و 1` });
            }
        }

        // ✅ FIX: Find the canonical Settings doc first, then update by its exact _id
        // This prevents mismatches when findOneAndUpdate({}) targets a different doc than getSettings()
        let existingSettings = await Settings.findOne().sort({ updatedAt: -1 });
        let settings;

        if (existingSettings) {
            // Update the exact document that getSettings() reads
            settings = await Settings.findByIdAndUpdate(
                existingSettings._id,
                { $set: updates },
                { new: true, runValidators: true }
            );
            logger.info(`✅ Settings updated: _id=${existingSettings._id}`);
        } else {
            // No settings doc yet — create one
            settings = await Settings.create(updates);
            logger.info(`✅ Settings created: _id=${settings._id}`);
        }

        // ✅ CRITICAL: Sync credit_limit to ALL captains BEFORE sending response
        if (req.body.defaultCreditLimit !== undefined) {
            const newLimit = Number(req.body.defaultCreditLimit);
            if (!isNaN(newLimit) && newLimit <= 0) {
                // ✅ FIX: Use $in to cover ALL possible role values for captains
                // (some legacy records might have 'driver' instead of 'captain')
                const result = await User.updateMany(
                    { role: { $in: ['captain', 'driver'] } },
                    { $set: { credit_limit: newLimit } }
                );
                logger.info(`✅ Credit limit synced → ${newLimit} | captains updated: ${result.modifiedCount}`);

                // Also update any captain who might have null/missing credit_limit
                const fixNull = await User.updateMany(
                    { role: { $in: ['captain', 'driver'] }, credit_limit: { $exists: false } },
                    { $set: { credit_limit: newLimit } }
                );
                if (fixNull.modifiedCount > 0) {
                    logger.info(`🔧 Fixed ${fixNull.modifiedCount} captains with missing credit_limit field`);
                }
            }
        }

        logger.info(`✅ Settings saved by admin ${req.user._id}:`, Object.keys(updates).join(', '));
        res.json({ message: 'تم تحديث الإعدادات بنجاح', settings });
    } catch (error) {
        logger.error('Settings Update Error:', error);
        res.status(500).json({ message: 'فشل حفظ الإعدادات: ' + error.message });
    }
});


// =========================================================
// 🗺️ منطقة التوصيل (Delivery Zone / Geofencing)
// =========================================================

// @route   GET /api/admin/delivery-zone
// @desc    جلب إحداثيات منطقة التوصيل (متاح للجميع لكي يتمكن التطبيق من فحص النطاق)
router.get('/delivery-zone', protect, async (req, res) => {
    try {
        const settings = await Settings.getSettings();
        res.json({ deliveryZone: settings.deliveryZone || [] });
    } catch (error) {
        logger.error("Delivery Zone GET Error:", error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/delivery-zone
// @desc    حفظ إحداثيات منطقة التوصيل الجديدة (أدمن فقط)
router.put('/delivery-zone', protect, adminOnly, async (req, res) => {
    try {
        const { deliveryZone } = req.body;

        if (!Array.isArray(deliveryZone) || deliveryZone.length < 3) {
            return res.status(400).json({ message: 'يجب أن تحتوي منطقة التوصيل على 3 نقاط على الأقل' });
        }

        // Validate each coordinate
        for (const point of deliveryZone) {
            if (typeof point.lat !== 'number' || typeof point.lng !== 'number') {
                return res.status(400).json({ message: 'تنسيق الإحداثيات غير صحيح — يجب أن تكون أرقاماً' });
            }
        }

        // ✅ FIX #13: Use getSettings() to always get the canonical document (sorted by updatedAt)
        // Raw findOne() without sort could update a stale/wrong doc when duplicates exist
        let settings = await Settings.getSettings();
        if (!settings._id) {
            settings = await Settings.create({ deliveryZone });
        } else {
            await Settings.findByIdAndUpdate(settings._id, {
                $set: { deliveryZone, updatedBy: req.user._id }
            });
        }

        // Broadcast the update to all connected clients via Socket.IO
        const io = req.app.get('io');
        if (io) {
            io.emit('delivery_zone_updated', { deliveryZone });
        }

        res.json({ message: '✅ تم حفظ منطقة التوصيل بنجاح', deliveryZone });
    } catch (error) {
        logger.error("Delivery Zone PUT Error:", error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 🗑️ الجزء السادس: الحذف والتعديل الشامل (Super Admin)
// =========================================================

// @route   DELETE /api/admin/users/:id
// @desc    حذف مستخدم نهائياً
router.delete('/users/:id', protect, adminOnly, async (req, res) => {
    try {
        if (req.user._id.toString() === req.params.id) {
            return res.status(400).json({ message: 'لا يمكنك حذف حسابك الشخصي!' });
        }
        const user = await User.findByIdAndDelete(req.params.id);
        if (!user) return res.status(404).json({ message: 'المستخدم غير موجود' });
        res.json({ message: 'تم حذف المستخدم بنجاح' });
    } catch (error) {
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/users/:id
// @desc    تعديل بيانات المستخدم شاملة
router.put('/users/:id', protect, adminOnly, async (req, res) => {
    try {
        const { name, email, phone, role, wallet, vehicleType } = req.body;
        const user = await User.findById(req.params.id);

        if (!user) return res.status(404).json({ message: 'المستخدم غير موجود' });

        // BUG #26 FIX: Prevent privilege escalation — admin cannot promote users to admin role
        if (role !== undefined && !['client', 'captain', 'merchant'].includes(role)) {
            return res.status(403).json({ message: 'لا يمكنك تعيين دور admin لأي مستخدم' });
        }

        user.name   = name   || user.name;
        user.email  = email  || user.email;
        user.phone  = phone  || user.phone;
        user.role   = role   || user.role;
        user.wallet = wallet !== undefined ? wallet : user.wallet;

        // 💳 Financial fields for manual admin control
        if (req.body.wallet_balance !== undefined) {
            const parsedBalance = Number(req.body.wallet_balance);
            if (!isNaN(parsedBalance)) user.wallet_balance = parsedBalance;
        }
        if (req.body.credit_limit !== undefined) {
            const parsedLimit = Number(req.body.credit_limit);
            if (!isNaN(parsedLimit)) user.credit_limit = parsedLimit;
        }
        if (req.body.is_blocked !== undefined) {
            user.is_blocked = Boolean(req.body.is_blocked);
        }

        if (role === 'captain' && vehicleType) {
            user.vehicleType = vehicleType;
        }

        // ✅ FIX: Set password directly — the pre('save') hook in User.js will hash it
        if (req.body.password) {
            user.password = req.body.password;
        }

        await user.save();
        
        const userObj = user.toObject();
        delete userObj.password;
        delete userObj.fcmToken;
        delete userObj.resetCode;
        delete userObj.verificationCode;
        
        res.json({ message: 'تم تحديث بيانات المستخدم بنجاح', user: userObj });
    } catch (error) {
        logger.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   DELETE /api/admin/orders/:id
// @desc    حذف طلب نهائياً
router.delete('/orders/:id', protect, adminOnly, async (req, res) => {
    try {
        const order = await Order.findByIdAndDelete(req.params.id);
        if (!order) return res.status(404).json({ message: 'الطلب غير موجود' });

        // ✅ Emit socket event so client/captain remove it in real-time
        const io = req.app.get('io');
        if (io) {
            io.emit('new_order_available'); // Force captains to refresh available orders
            if (order.client) io.to(order.client.toString()).emit('order_status_updated', { orderId: order._id, status: 'deleted' });
            if (order.captain) io.to(order.captain.toString()).emit('order_status_updated', { orderId: order._id, status: 'deleted' });
            io.emit('admin_order_update', { orderId: order._id, status: 'deleted' });
        }

        res.json({ message: 'تم حذف الطلب بنجاح' });
    } catch (error) {
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/orders/:id
// @desc    تعديل بيانات الطلب شاملة
router.put('/orders/:id', protect, adminOnly, async (req, res) => {
    try {
        const order = await Order.findById(req.params.id);
        if (!order) return res.status(404).json({ message: 'الطلب غير موجود' });

        const oldStatus = order.status; // ✅ Track old status to detect changes

        // تحديث الحقول المسموح بها
        if (req.body.status) order.status = req.body.status;
        if (req.body.price !== undefined) {
            order.price = req.body.price;
            // ✅ FIX #9: Auto-recalculate appFee & netRevenue when price changes
            try {
                const liveSettings = await Settings.getSettings();
                const commissionRate = liveSettings.commissionRate ?? 0.15;
                order.appFee = order.price * commissionRate;
                order.netRevenue = order.price - order.appFee;
            } catch (settingsErr) {
                logger.warn('Could not load settings for fee recalculation, keeping existing fees');
            }
        }
        // Only allow explicit appFee override if price was NOT changed
        if (req.body.appFee !== undefined && req.body.price === undefined) order.appFee = req.body.appFee;

        // تحديث تفاصيل الاستلام والتسليم إذا وجدت
        if (req.body.pickup) order.pickup = { ...order.pickup, ...req.body.pickup };
        if (req.body.dropoff) order.dropoff = { ...order.dropoff, ...req.body.dropoff };

        await order.save();

        // ✅ Emit socket event and notify if status changed (e.g. restored from cancelled)
        if (oldStatus !== order.status) {
            const io = req.app.get('io');
            const { sendNotification } = require('../utils/notificationHelper');
            
            if (io) {
                io.emit('admin_order_update', { orderId: order._id, status: order.status });
                if (order.status === 'pending' || order.status === 'scheduled') {
                    io.emit('new_order_available');
                }
            }
            
            if (order.client) {
                if (io) io.to(order.client.toString()).emit('order_status_updated', { orderId: order._id, status: order.status });
                await sendNotification(req.app, {
                    userId: order.client,
                    title: 'تحديث حالة الطلب',
                    message: `تم تغيير حالة طلبك رقم ${order._id.toString().slice(-6)} إدارياً إلى: ${order.status}`,
                    type: 'order_update',
                    relatedId: order._id
                });
            }
            if (order.captain) {
                if (io) io.to(order.captain.toString()).emit('order_status_updated', { orderId: order._id, status: order.status });
                await sendNotification(req.app, {
                    userId: order.captain,
                    title: 'تحديث حالة الطلب',
                    message: `تم تغيير حالة الطلب رقم ${order._id.toString().slice(-6)} إدارياً إلى: ${order.status}`,
                    type: 'order_update',
                    relatedId: order._id
                });
            }
        }

        res.json({ message: 'تم تحديث الطلب بنجاح', order });
    } catch (error) {
        res.status(500).json({ message: 'Server Error' });
    }
});

router.get('/emergency-alerts', protect, adminOnly, async (req, res) => {
    try {
        const EmergencyAlert = require('../models/EmergencyAlert');
        const alerts = await EmergencyAlert.find().populate('captain', 'name phone').sort({ createdAt: -1 }).limit(50);
        res.json(alerts);
    } catch (error) {
        res.status(500).json({ message: 'خطأ' });
    }
});

// @route   GET /api/admin/active-captains
// @desc    Get all captains with location data (for live map)
// ✅ Returns ALL captains regardless of location freshness — Admin panel needs full visibility
router.get('/active-captains', protect, adminOnly, async (req, res) => {
    try {
        const captains = await User.find({ role: 'captain' })
            .select('name phone isActive currentLocation wallet_balance is_blocked credit_limit role vehicleType');

        const result = captains.map(captain => ({
            _id: captain._id,
            name: captain.name,
            phone: captain.phone,
            role: captain.role,
            vehicleType: captain.vehicleType,
            isActive: captain.isActive,
            is_blocked: captain.is_blocked,
            wallet_balance: captain.wallet_balance,
            credit_limit: captain.credit_limit,
            location: captain.currentLocation,
            currentLocation: captain.currentLocation,
            // ✅ Calculate if location is fresh (updated within last 5 minutes)
            locationFresh: captain.currentLocation?.updatedAt
                ? (Date.now() - new Date(captain.currentLocation.updatedAt).getTime()) < 5 * 60 * 1000
                : false
        }));

        res.json(result);
    } catch (error) {
        logger.error("Live Map Error:", error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 🔔 إرسال الإشعارات (Admin Notifications)
// =========================================================

// @route   POST /api/admin/send-notification
// @desc    إرسال إشعار لمستخدم محدد أو لمجموعة
router.post('/send-notification', protect, adminOnly, async (req, res) => {
    try {
        const { userId, title, message, target } = req.body;
        // target: 'user' (single), 'all' (everyone), 'clients', 'captains'

        if (!title || !message) {
            return res.status(400).json({ message: 'العنوان والرسالة مطلوبان' });
        }

        const { sendNotification } = require('../utils/notificationHelper');
        const { sendPushToMany } = require('../utils/firebasePush');
        const Notification = require('../models/Notification');

        if (target === 'user' && userId) {
            // Send to single user
            await sendNotification(req.app, {
                userId,
                title,
                message,
                type: 'system',
                relatedId: null
            });
            return res.json({ message: 'تم إرسال الإشعار بنجاح', sentTo: 1 });
        }

        // Broadcast: find target users
        let query = {};
        if (target === 'clients') query = { role: 'client' };
        else if (target === 'captains') query = { role: 'captain' };
        // else 'all' — no filter

        const users = await User.find(query).select('_id fcmToken');

        // 1. Send via Socket.IO to online users (Non-blocking)
        const io = req.app.get('io');
        if (io) {
            users.forEach(u => {
                io.to(u._id.toString()).emit('new_notification', { title, message, type: 'system' });
            });
        }

        // 🚀 BATCH PROCESSING: Save to DB and Send Push efficiently
        const batchSize = 500;
        let totalInserted = 0;
        let pushTokens = [];

        for (let i = 0; i < users.length; i += batchSize) {
            const batch = users.slice(i, i + batchSize);

            // Collect tokens for push
            batch.forEach(u => {
                if (u.fcmToken) pushTokens.push(u.fcmToken);
            });

            // Prepare DB notifications
            const notificationsCount = batch.map(u => ({
                user: u._id,
                title,
                message,
                type: 'system',
                isRead: false
            }));

            // Insert to DB in batches
            await Notification.insertMany(notificationsCount);
            totalInserted += notificationsCount.length;
        }

        // Send FCM Push in one call (or chunk inside sendPushToMany if needed, firebase-admin handles up to 500 tokens inherently)
        if (pushTokens.length > 0) {
            await sendPushToMany(pushTokens, title, message);
        }

        res.json({
            message: 'تم إرسال الإشعار بنجاح',
            sentTo: totalInserted,
            pushSent: pushTokens.length
        });

    } catch (error) {
        logger.error('Send Notification Error:', error);
        res.status(500).json({ message: 'فشل في إرسال الإشعار' });
    }
});


// =========================================================
// 💳 إدارة طلبات سداد المديونية (Payment Requests)
// =========================================================

// @route   GET /api/admin/payment-requests
// @desc    جلب جميع طلبات السداد المعلقة
router.get('/payment-requests', protect, adminOnly, async (req, res) => {
    try {
        const PaymentRequest = require('../models/PaymentRequest');
        const { status } = req.query; // optional filter: pending|approved|rejected

        const query = status ? { status } : {};
        const requests = await PaymentRequest.find(query)
            .populate('captainId', 'name phone wallet_balance credit_limit is_blocked')
            .populate('reviewedBy', 'name')
            .sort({ createdAt: -1 });

        res.json(requests);
    } catch (error) {
        logger.error('Payment Requests Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/payment-requests/:id/approve
// @desc    الموافقة على طلب السداد — إضافة المبلغ المسدد للرصيد + رفع الحجب إذا لزم
router.put('/payment-requests/:id/approve', protect, adminOnly, async (req, res) => {
    try {
        const PaymentRequest = require('../models/PaymentRequest');
        const payReq = await PaymentRequest.findById(req.params.id);
        if (!payReq) return res.status(404).json({ message: 'الطلب غير موجود' });
        if (payReq.status !== 'pending') {
            return res.status(400).json({ message: 'هذا الطلب تمت مراجعته بالفعل' });
        }

        let captain = await User.findById(payReq.captainId);
        if (!captain) return res.status(404).json({ message: 'الكابتن غير موجود' });

        const prevBalance = captain.wallet_balance ?? 0;
        const debt = Math.abs(prevBalance < 0 ? prevBalance : 0); // المديونية = القيمة المطلقة للرصيد السالب

        // 📥 Allow admin to override the deducted amount (optional)
        // If body.deductAmount is provided, use it instead of payReq.amount
        // This lets admin pay only part of the debt or correct mistakes
        const requestedAmount = req.body.deductAmount !== undefined
            ? Number(req.body.deductAmount)
            : Number(payReq.amount);

        if (isNaN(requestedAmount) || requestedAmount <= 0) {
            return res.status(400).json({ message: 'المبلغ غير صالح' });
        }

        // ⚠️ Check if amount exceeds debt
        const exceedsDebt = requestedAmount > debt;
        const overpayment = exceedsDebt ? (requestedAmount - debt) : 0;

        // If admin didn't confirm overpayment, reject and inform
        if (exceedsDebt && !req.body.confirmOverpayment) {
            return res.status(400).json({
                message: 'overpayment_warning',
                debt,
                requestedAmount,
                overpayment,
                warningMessage: `المبلغ المسدد (${requestedAmount} ج.س) أكثر من المديونية الحالية (${debt} ج.س) بمقدار ${overpayment} ج.س. هل تريد المتابعة؟`
            });
        }

        // ✅ Atomic update using $inc
        captain = await User.findByIdAndUpdate(
            payReq.captainId,
            { $inc: { wallet_balance: requestedAmount } },
            { new: true }
        );

        let changed = false;
        // ✅ CREDIT CEILING FIX: balance must never exceed 0 (no positive balance allowed)
        if (captain.wallet_balance > 0) {
            captain.wallet_balance = 0; // safety cap at 0
            changed = true;
        }

        // رفع الحجب فقط إذا الرصيد ضمن الحد الائتماني
        const creditLimit = captain.credit_limit ?? -5000;
        if (captain.wallet_balance >= creditLimit && captain.is_blocked) {
            captain.is_blocked = false;
            changed = true;
        }
        
        if (changed) {
            await captain.save();
        }
        
        const newBalance = captain.wallet_balance;
        const actualDeduction = requestedAmount; // We added this, though it may have been capped

        // تحديث الطلب
        payReq.status = 'approved';
        payReq.reviewedBy = req.user._id;
        payReq.reviewedAt = new Date();
        if (req.body.deductAmount !== undefined) {
            payReq.deductedAmount = actualDeduction;
        }
        await payReq.save();

        // 📡 Real-Time Unblock: notify captain immediately via socket
        const ioInst = req.app.get('io');
        if (ioInst && !captain.is_blocked) {
            ioInst.to(captain._id.toString()).emit('payment_approved', {
                newBalance: captain.wallet_balance,
                message: `تم خصم ${actualDeduction} ج.س من مديونيتك. الرصيد الحالي: ${captain.wallet_balance} ج.س`
            });
        }

        // 🔔 إشعار للكابتن
        const { sendNotification } = require('../utils/notificationHelper');
        const remainingDebt = Math.abs(captain.wallet_balance);
        const notifMsg = remainingDebt > 0
            ? `تمت الموافقة على دفعتك بمبلغ ${actualDeduction} ج.س. المتبقي عليك: ${remainingDebt} ج.س`
            : `تمت الموافقة على دفعتك بمبلغ ${actualDeduction} ج.س. تم تصفير المديونية بنجاح!`;

        await sendNotification(req.app, {
            userId: captain._id,
            title: '✅ تم قبول سداد المديونية',
            message: notifMsg,
            type: 'system',
            relatedId: payReq._id
        });

        logger.info(`✅ PaymentRequest ${payReq._id} APPROVED | Captain balance: ${prevBalance} → ${captain.wallet_balance} | Deducted: ${actualDeduction} | Blocked: ${captain.is_blocked}`);

        res.json({
            message: 'تمت الموافقة على السداد بنجاح',
            newBalance: captain.wallet_balance,
            deductedAmount: actualDeduction,
            remainingDebt: Math.abs(captain.wallet_balance),
            isBlocked: captain.is_blocked
        });
    } catch (error) {
        logger.error('Approve Payment Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// @route   PUT /api/admin/payment-requests/:id/reject
// @desc    رفض طلب السداد مع إشعار الكابتن بالسبب
router.put('/payment-requests/:id/reject', protect, adminOnly, async (req, res) => {
    try {
        const PaymentRequest = require('../models/PaymentRequest');
        const { adminNote } = req.body;

        const payReq = await PaymentRequest.findById(req.params.id)
            .populate('captainId', 'name _id');
        if (!payReq) return res.status(404).json({ message: 'الطلب غير موجود' });
        if (payReq.status !== 'pending') {
            return res.status(400).json({ message: 'هذا الطلب تمت مراجعته بالفعل' });
        }

        payReq.status = 'rejected';
        payReq.adminNote = adminNote || 'لم يتم تحديد السبب';
        payReq.reviewedBy = req.user._id;
        payReq.reviewedAt = new Date();
        await payReq.save();

        // 🔔 إشعار للكابتن
        const { sendNotification } = require('../utils/notificationHelper');
        await sendNotification(req.app, {
            userId: payReq.captainId._id,
            title: '❌ تم رفض إشعار السداد',
            message: `تم رفض دفعتك بمبلغ ${payReq.amount} ج.س. السبب: ${payReq.adminNote}. الرجاء التواصل مع الإدارة.`,
            type: 'system',
            relatedId: payReq._id
        });

        res.json({ message: 'تم رفض الطلب وإشعار الكابتن' });
    } catch (error) {
        logger.error('Reject Payment Error:', error);
        res.status(500).json({ message: 'Server Error' });
    }
});

// =========================================================
// 📣 Broadcast Notifications — إرسال إشعارات جماعية
// =========================================================

// @route   GET /api/admin/users/search?q=...
// @desc    البحث عن مستخدم بالاسم أو الهاتف (للإشعار المحدد)
router.get('/users/search', protect, adminOnly, async (req, res) => {
    try {
        const q = (req.query.q || '').trim();
        if (!q || q.length < 2) return res.json([]);

        const users = await User.find({
            $or: [
                { name: { $regex: q, $options: 'i' } },
                { phone: { $regex: q, $options: 'i' } }
            ],
            role: { $in: ['client', 'captain', 'merchant'] }
        })
        .select('name phone role fcmToken')
        .limit(10);

        res.json(users);
    } catch (err) {
        logger.error('User Search Error:', err);
        res.status(500).json({ message: 'Server error' });
    }
});

// @route   POST /api/admin/broadcast
// @desc    إرسال إشعار جماعي أو مخصص
// target: 'all' | 'clients' | 'captains' | 'merchants' | 'user'
// userId: required when target === 'user'
router.post('/broadcast', protect, adminOnly, async (req, res) => {
    try {
        const { target, userId, title, message } = req.body;
        if (!title || !message) return res.status(400).json({ message: 'العنوان والرسالة مطلوبان' });

        const { sendPush, sendPushToMany } = require('../utils/firebasePush');
        const { sendNotification } = require('../utils/notificationHelper');
        const Notification = require('../models/Notification');

        let users = [];

        if (target === 'user') {
            if (!userId) return res.status(400).json({ message: 'userId مطلوب لإرسال إشعار محدد' });
            const user = await User.findById(userId).select('name phone role fcmToken');
            if (!user) return res.status(404).json({ message: 'المستخدم غير موجود' });
            users = [user];

        } else if (target === 'clients') {
            users = await User.find({ role: 'client', fcmToken: { $exists: true, $ne: '' } }).select('_id fcmToken');
        } else if (target === 'captains') {
            users = await User.find({ role: 'captain', fcmToken: { $exists: true, $ne: '' } }).select('_id fcmToken');
        } else if (target === 'merchants') {
            users = await User.find({ role: 'merchant', fcmToken: { $exists: true, $ne: '' } }).select('_id fcmToken');
        } else { // 'all'
            users = await User.find({
                role: { $in: ['client', 'captain', 'merchant'] },
                fcmToken: { $exists: true, $ne: '' }
            }).select('_id fcmToken');
        }

        if (users.length === 0) {
            return res.json({ success: 0, failure: 0, total: 0, message: 'لا يوجد مستخدمون مؤهلون للإرسال' });
        }

        // 1. Save in-app notifications in bulk
        const notifDocs = users.map(u => ({
            user: u._id,
            title,
            message,
            type: 'system',
            isRead: false
        }));
        await Notification.insertMany(notifDocs);

        // 2. Emit via socket
        const io = req.app.get('io');
        if (io) {
            users.forEach(u => {
                io.to(u._id.toString()).emit('new_notification', { title, message });
            });
        }

        // 3. Send FCM push
        const tokens = users.map(u => u.fcmToken).filter(Boolean);
        const { success, failure } = tokens.length > 0
            ? await sendPushToMany(tokens, title, message, { type: 'broadcast' })
            : { success: 0, failure: 0 };

        logger.info(`📣 Broadcast [${target}]: ${success} sent, ${failure} failed, ${users.length} total`);
        res.json({ success, failure, total: users.length });

    } catch (err) {
        logger.error('Broadcast Error:', err);
        res.status(500).json({ message: 'Server error: ' + err.message });
    }
});

module.exports = router;