<?php
/**
 * ADMIN NOTIFICATIONS SIDEBAR
 * Include this in admin dashboard
 * 
 * Usage:
 * include(__DIR__ . '/notifications_sidebar.php');
 */

require_once(__DIR__ . '/../../classes/Database.php');
require_once(__DIR__ . '/../../classes/Payment.php');

$db = Database::getInstance();
$payment = new Payment();

$pendingApprovals = $payment->getPendingApprovals(10);
$paymentDetails = $payment->getPaymentDetails(); // Get admin payment settings including QR code
$totalPending = count($pendingApprovals);
$totalRevenue = $db->fetch('SELECT SUM(amount) as total FROM payment_orders WHERE status = "completed"')['total'] ?? 0;
?>

<style>
    .notifications-sidebar {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.08);
        position: sticky;
        top: 20px;
    }

    .notifications-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 15px;
    }

    .notifications-header h5 {
        margin: 0;
        color: #333;
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .badge-count {
        background: #ef4444;
        color: white;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 700;
    }

    .refresh-btn {
        background: none;
        border: none;
        color: #667eea;
        cursor: pointer;
        font-size: 16px;
        transition: all 0.3s ease;
    }

    .refresh-btn:hover {
        transform: rotate(180deg);
    }

    .refresh-btn.spinning {
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    .stats-mini {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin-bottom: 15px;
    }

    .stat-mini-box {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 12px;
        border-radius: 8px;
        text-align: center;
    }

    .stat-mini-box.revenue {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }

    .stat-mini-box .label {
        font-size: 11px;
        opacity: 0.9;
        margin-bottom: 5px;
    }

    .stat-mini-box .value {
        font-size: 20px;
        font-weight: 700;
    }

    .notifications-list {
        max-height: 400px;
        overflow-y: auto;
    }

    .notification-item {
        background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
        border: 1px solid #e0e5ff;
        border-left: 4px solid #667eea;
        padding: 12px;
        border-radius: 8px;
        margin-bottom: 10px;
        transition: all 0.3s ease;
        font-size: 12px;
    }

    .notification-item.new {
        border-left-color: #10b981;
        background: linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.15);
    }

    .notification-item:hover {
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
        transform: translateY(-2px);
    }

    .notification-item.approve {
        border-left-color: #10b981;
    }

    .notification-user {
        font-weight: 600;
        color: #1c1c1e;
        font-size: 12px;
        margin-bottom: 6px;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .notification-user-email {
        font-size: 10px;
        color: #888;
        font-weight: 400;
    }

    .notification-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
        font-size: 11px;
        color: #666;
        margin: 6px 0;
    }

    .notification-amount {
        font-weight: 700;
        color: #10b981;
        font-size: 13px;
    }

    .notification-time {
        font-size: 10px;
        color: #999;
        margin: 6px 0;
    }

    .notification-detail-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 3px;
    }

    .notification-detail-label {
        color: #999;
        font-weight: 500;
        min-width: 50px;
    }

    .notification-detail-value {
        color: #333;
        font-weight: 600;
        text-align: right;
        word-break: break-all;
        flex: 1;
    }

    .notification-screenshot-btn {
        width: 100%;
        padding: 6px;
        margin: 6px 0;
        background: #3b82f6;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 10px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.2s ease;
    }

    .notification-screenshot-btn:hover {
        background: #2563eb;
    }

    .empty-notifications {
        text-align: center;
        padding: 30px 10px;
        color: #999;
    }

    .empty-notifications i {
        font-size: 32px;
        display: block;
        margin-bottom: 10px;
        opacity: 0.5;
    }

    .action-buttons {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 6px;
        margin-top: 8px;
    }

    .action-btn-mini {
        padding: 10px 8px;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.2s ease;
        width: 100%;
        white-space: nowrap;
    }

    .action-btn-approve {
        background: #10b981;
        color: white;
    }

    .action-btn-approve:hover:not(:disabled) {
        background: #059669;
        transform: scale(1.02);
    }

    .action-btn-reject {
        background: #ef4444;
        color: white;
    }

    .action-btn-reject:hover:not(:disabled) {
        background: #dc2626;
        transform: scale(1.02);
    }

    .action-btn-mini:disabled,
    .action-btn-mini.disabled {
        opacity: 0.6;
        cursor: not-allowed !important;
        pointer-events: none;
    }

    .notification-popup {
        position: fixed;
        top: 20px;
        right: 20px;
        background: white;
        border-left: 4px solid #10b981;
        padding: 15px 20px;
        border-radius: 8px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        max-width: 350px;
        animation: slideIn 0.3s ease;
        z-index: 9999;
    }

    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    @keyframes slideOut {
        to {
            transform: translateX(400px);
            opacity: 0;
        }
    }

    .notification-popup.error {
        border-left-color: #ef4444;
    }

    .notification-popup-close {
        float: right;
        background: none;
        border: none;
        cursor: pointer;
        color: #999;
        font-size: 20px;
    }

    .notification-popup-title {
        font-weight: 700;
        color: #333;
        margin-bottom: 5px;
        margin-right: 20px;
    }

    .notification-popup-message {
        color: #666;
        font-size: 13px;
    }

    /* MOBILE RESPONSIVE */
    @media (max-width: 768px) {
        .notifications-sidebar {
            padding: 15px;
            position: relative;
        }

        .notifications-header h5 {
            font-size: 16px;
        }

        .badge-count {
            padding: 3px 8px;
            font-size: 11px;
        }

        .stats-mini {
            gap: 8px;
        }

        .stat-mini-box {
            padding: 10px;
        }

        .stat-mini-box .label {
            font-size: 10px;
        }

        .stat-mini-box .value {
            font-size: 16px;
        }

        .notifications-list {
            max-height: 350px;
        }

        .notification-item {
            padding: 10px;
            margin-bottom: 8px;
            font-size: 11px;
        }

        .notification-user {
            font-size: 11px;
        }

        .notification-user-email {
            font-size: 9px;
        }

        .notification-details {
            font-size: 10px;
        }

        .notification-detail-label {
            font-size: 9px;
        }

        .notification-detail-value {
            font-size: 9px;
        }

        .notification-time {
            font-size: 9px;
        }

        .notification-amount {
            font-size: 11px;
        }

        .notification-screenshot-btn {
            padding: 5px;
            font-size: 9px;
        }

        .action-buttons {
            gap: 4px;
        }

        .action-btn-mini {
            padding: 8px;
            font-size: 11px;
        }

        .notification-popup {
            top: 10px;
            right: 10px;
            left: 10px;
            max-width: none;
        }
    }

    @media (max-width: 480px) {
        .notifications-sidebar {
            padding: 12px;
        }

        .notifications-header h5 {
            font-size: 14px;
        }

        .badge-count {
            padding: 2px 6px;
            font-size: 10px;
        }

        .stat-mini-box {
            padding: 8px;
        }

        .stat-mini-box .label {
            font-size: 9px;
        }

        .stat-mini-box .value {
            font-size: 14px;
        }

        .notifications-list {
            max-height: 300px;
        }

        .notification-item {
            padding: 8px;
            margin-bottom: 6px;
            font-size: 10px;
        }

        .notification-user {
            font-size: 10px;
        }

        .notification-user-email {
            font-size: 8px;
        }

        .notification-detail-label {
            font-size: 8px;
        }

        .notification-detail-value {
            font-size: 8px;
        }

        .notification-screenshot-btn {
            padding: 4px;
            font-size: 8px;
        }

        .action-btn-mini {
            padding: 6px;
            font-size: 10px;
        }

        .notification-popup {
            top: 5px;
            right: 5px;
            left: 5px;
        }
    }
</style>

<div class="notifications-sidebar">
    <!-- Header -->
    <div class="notifications-header">
        <h5>
            <i class="fas fa-bell"></i> Notifications
            <?php if ($totalPending > 0): ?>
            <span class="badge-count" id="badge-count"><?php echo $totalPending; ?></span>
            <?php endif; ?>
        </h5>
        <button class="refresh-btn" id="refresh-notifications" onclick="refreshNotifications()">
            <i class="fas fa-sync-alt"></i>
        </button>
    </div>

    <!-- Mini Stats -->
    <div class="stats-mini">
        <div class="stat-mini-box">
            <div class="label">⏳ Pending</div>
            <div class="value" id="pending-count"><?php echo $totalPending; ?></div>
        </div>
        <div class="stat-mini-box revenue">
            <div class="label">💰 Revenue</div>
            <div class="value">₹<?php echo number_format($totalRevenue / 1000, 0); ?>K</div>
        </div>
    </div>

    <!-- Notifications List -->
    <div class="notifications-list" id="notifications-list">
        <?php if ($totalPending > 0): ?>
            <?php foreach ($pendingApprovals as $notification): ?>
            <div class="notification-item new" id="notification-<?php echo $notification['id']; ?>">
                <div class="notification-user">
                    <div>
                        <strong><?php echo htmlspecialchars($notification['name']); ?></strong>
                        <div class="notification-user-email">📧 <?php echo htmlspecialchars($notification['email']); ?></div>
                    </div>
                </div>
                <div class="notification-details">
                    <div>
                        <div class="notification-detail-row">
                            <span class="notification-detail-label">Order:</span>
                            <span class="notification-detail-value"><?php echo htmlspecialchars($notification['order_id']); ?></span>
                        </div>
                    </div>
                    <div>
                        <div class="notification-detail-row">
                            <span class="notification-detail-label">UTR:</span>
                            <span class="notification-detail-value"><?php echo htmlspecialchars($notification['transaction_id'] ?? 'N/A'); ?></span>
                        </div>
                    </div>
                </div>
                <div class="notification-time">
                    Amount: <strong class="notification-amount">₹<?php echo number_format($notification['amount'], 2); ?></strong> | 
                    <i class="fas fa-clock"></i> <?php echo date('d M H:i', strtotime($notification['created_at'])); ?>
                </div>
                <?php if (!empty($notification['screenshot_path'])): ?>
                <button class="notification-screenshot-btn" onclick="viewScreenshot('<?php echo htmlspecialchars($notification['screenshot_path']); ?>')">
                    <i class="fas fa-image"></i> View Screenshot
                </button>
                <?php endif; ?>
                <?php if (!empty($paymentDetails['qr_code_path'])): ?>
                <button class="notification-screenshot-btn" style="background: #8b5cf6;" onclick="viewScreenshot('/extract/<?php echo htmlspecialchars($paymentDetails['qr_code_path']); ?>')">
                    <i class="fas fa-qrcode"></i> View QR Code
                </button>
                <?php endif; ?>
                <div class="action-buttons">
                    <button type="button" class="action-btn-mini action-btn-approve" onclick="event.preventDefault(); event.stopPropagation(); handleApprove('<?php echo addslashes($notification['order_id']); ?>', this); return false;">
                        ✓ Approve
                    </button>
                    <button type="button" class="action-btn-mini action-btn-reject" onclick="event.preventDefault(); event.stopPropagation(); handleReject('<?php echo addslashes($notification['order_id']); ?>', this); return false;">
                        ✕ Reject
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
        <div class="empty-notifications">
            <i class="fas fa-inbox"></i>
            <p>No pending approvals</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
    let autoRefreshInterval;

    function viewScreenshot(path) {
        const modal = document.createElement('div');
        modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 9999;';
        modal.onclick = () => modal.remove();
        
        const img = document.createElement('img');
        img.src = '/extract/' + path;
        img.style.cssText = 'max-width: 90vw; max-height: 90vh; border-radius: 8px; cursor: auto;';
        img.onclick = (e) => e.stopPropagation();
        
        const closeBtn = document.createElement('button');
        closeBtn.innerHTML = '×';
        closeBtn.style.cssText = 'position: absolute; top: 20px; right: 20px; background: white; border: none; font-size: 30px; cursor: pointer; width: 40px; height: 40px; border-radius: 50%;';
        closeBtn.onclick = () => modal.remove();
        
        modal.appendChild(img);
        modal.appendChild(closeBtn);
        document.body.appendChild(modal);
    }

    function startAutoRefresh() {
        autoRefreshInterval = setInterval(refreshNotifications, 5000); // Refresh every 5 seconds
    }

    function stopAutoRefresh() {
        clearInterval(autoRefreshInterval);
    }

    function refreshNotifications() {
        const btn = document.getElementById('refresh-notifications');
        btn.classList.add('spinning');

        fetch('/extract/admin/get_notifications.php')
            .then(response => response.json())
            .then(data => {
                btn.classList.remove('spinning');

                if (data.notifications.length > 0) {
                    document.getElementById('notifications-list').innerHTML = '';
                    const newCount = data.notifications.length;
                    document.getElementById('pending-count').textContent = newCount;
                    document.getElementById('badge-count').textContent = newCount;

                    data.notifications.forEach(notification => {
                        addNotificationItem(notification);
                    });

                    // Show popup for new notifications
                    if (data.is_new) {
                        showNotificationPopup(
                            '✅ New Payment Received',
                            'Payment from ' + data.notifications[0].name + ' - ₹' + data.notifications[0].amount
                        );
                    }
                } else {
                    document.getElementById('notifications-list').innerHTML = 
                        '<div class="empty-notifications"><i class="fas fa-inbox"></i><p>No pending approvals</p></div>';
                    document.getElementById('badge-count').style.display = 'none';
                }
            })
            .catch(error => {
                btn.classList.remove('spinning');
                console.error('Error refreshing notifications:', error);
            });
    }

    function addNotificationItem(notification) {
        const screenshotBtn = notification.screenshot_path ? `
            <button class="notification-screenshot-btn" onclick="viewScreenshot('${notification.screenshot_path.replace(/'/g, "\\'")}')">
                <i class="fas fa-image"></i> View Screenshot
            </button>
        ` : '';

        const html = `
            <div class="notification-item new" id="notification-${notification.id}">
                <div class="notification-user">
                    <div>
                        <strong>${escapeHtml(notification.name)}</strong>
                        <div class="notification-user-email">📧 ${escapeHtml(notification.email)}</div>
                    </div>
                </div>
                <div class="notification-details">
                    <div>
                        <div class="notification-detail-row">
                            <span class="notification-detail-label">Order:</span>
                            <span class="notification-detail-value">${escapeHtml(notification.order_id)}</span>
                        </div>
                    </div>
                    <div>
                        <div class="notification-detail-row">
                            <span class="notification-detail-label">UTR:</span>
                            <span class="notification-detail-value">${escapeHtml(notification.transaction_id || 'N/A')}</span>
                        </div>
                    </div>
                </div>
                <div class="notification-time">
                    Amount: <strong class="notification-amount">₹${parseFloat(notification.amount).toFixed(2)}</strong> | 
                    <i class="fas fa-clock"></i> Just now
                </div>
                ${screenshotBtn}
                <div class="action-buttons">
                    <button type="button" class="action-btn-mini action-btn-approve" onclick="event.preventDefault(); event.stopPropagation(); handleApprove('${notification.order_id}', this); return false;">
                        ✓ Approve
                    </button>
                    <button type="button" class="action-btn-mini action-btn-reject" onclick="event.preventDefault(); event.stopPropagation(); handleReject('${notification.order_id}', this); return false;">
                        ✕ Reject
                    </button>
                </div>
            </div>
        `;
        document.getElementById('notifications-list').insertAdjacentHTML('afterbegin', html);
    }

    function handleApprove(orderId, btn) {
        console.log('=== handleApprove CALLED ===');
        console.log('Order ID:', orderId);
        console.log('Button:', btn);
        
        if (!orderId || !btn) {
            console.error('Missing orderId or btn');
            alert('Error: Missing order ID or button');
            return;
        }
        
        btn.disabled = true;
        btn.textContent = '⏳ Processing...';
        
        const payload = { order_id: orderId };
        console.log('Payload:', JSON.stringify(payload));
        
        console.log('Fetching /extract/admin/approve_payment.php...');
        
        fetch('/extract/admin/approve_payment.php', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(payload)
        })
        .then(r => {
            console.log('Response received. Status:', r.status);
            if (!r.ok) {
                throw new Error('HTTP ' + r.status + ': ' + r.statusText);
            }
            return r.text();
        })
        .then(text => {
            console.log('Response text:', text);
            const data = JSON.parse(text);
            console.log('Parsed JSON:', data);
            
            if (data && data.status === 'success') {
                alert('✅ Payment Approved Successfully!');
                const card = btn.closest('.notification-item');
                if (card) {
                    card.style.opacity = '0.5';
                    setTimeout(() => card.remove(), 500);
                }
                setTimeout(() => refreshNotifications(), 1000);
            } else {
                const errMsg = (data && data.message) ? data.message : 'Unknown error';
                alert('❌ Error: ' + errMsg);
                console.error('Server error:', data);
                btn.disabled = false;
                btn.textContent = '✓ Approve';
            }
        })
        .catch(e => {
            console.error('Fetch error:', e);
            alert('❌ Error: ' + e.message);
            btn.disabled = false;
            btn.textContent = '✓ Approve';
        });
    }

    function handleReject(orderId, btn) {
        btn.disabled = true;
        btn.textContent = '⏳ Processing...';
        
        console.log('Rejecting order:', orderId);
        
        const payload = { order_id: orderId };
        console.log('Sending payload:', JSON.stringify(payload));
        
        fetch('/extract/admin/reject_payment.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
        .then(r => {
            console.log('Response received, status:', r.status);
            return r.json();
        })
        .then(data => {
            console.log('JSON parsed:', data);
            if (data && data.status === 'success') {
                alert('✅ Payment Rejected!');
                const card = btn.closest('.notification-item');
                if (card) {
                    card.style.opacity = '0.5';
                    setTimeout(() => card.remove(), 500);
                }
                setTimeout(() => refreshNotifications(), 1000);
            } else {
                alert('❌ Error: ' + (data && data.message ? data.message : 'Unknown error'));
                btn.disabled = false;
                btn.textContent = '✕ Reject';
            }
        })
        .catch(e => {
            console.error('Network error:', e);
            alert('❌ Network Error: ' + e.message);
            btn.disabled = false;
            btn.textContent = '✕ Reject';
        });
    }
                if (data.status === 'success') {
                    showNotificationPopup('❌ Payment Rejected', 'User will receive refund notification');
                    setTimeout(refreshNotifications, 1000);
                } else {
                    alert('Error: ' + data.message);
                    btn.disabled = false;
                }
            });
        }
    }

    function showNotificationPopup(title, message) {
        const popup = document.createElement('div');
        popup.className = 'notification-popup';
        popup.innerHTML = `
            <button class="notification-popup-close" onclick="this.parentElement.remove()">×</button>
            <div class="notification-popup-title">${title}</div>
            <div class="notification-popup-message">${message}</div>
        `;
        document.body.appendChild(popup);

        setTimeout(() => {
            popup.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => popup.remove(), 300);
        }, 5000);
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Start auto-refresh when page loads
    document.addEventListener('DOMContentLoaded', startAutoRefresh);

    // Stop auto-refresh when page loses focus
    window.addEventListener('blur', stopAutoRefresh);
    window.addEventListener('focus', startAutoRefresh);
</script>