<?php
/**
 * Guards - My Payments/Salary
 * View salary records and payment history
 */

$db = $GLOBALS['db'];

// Verify guard access
$user = $db->fetch("SELECT id, name FROM users WHERE id = ? AND role = 'guard'", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=dashboard');
    exit();
}

// Get salary information
$salary = $db->fetch(
    "SELECT * FROM staff_salaries WHERE staff_id = ? ORDER BY created_at DESC LIMIT 1",
    [$_SESSION['user_id']]
);

// Get payment records - guards salaries are tracked in staff_salaries table
$filters = [
    'order' => $_GET['order'] ?? 'created_at',
    'sort' => $_GET['sort'] ?? 'desc',
    'search' => $_GET['search'] ?? ''
];

$query = "SELECT s.*, u.name as staff_name
          FROM staff_salaries s
          JOIN users u ON s.staff_id = u.id
          WHERE s.staff_id = ?";
$params = [$_SESSION['user_id']];

// Search filter
if (!empty($filters['search'])) {
    $query .= " AND (s.salary_month LIKE ? OR s.notes LIKE ?)";
    $search = '%' . $filters['search'] . '%';
    array_push($params, $search, $search);
}

// Order and sort
$allowedColumns = ['created_at', 'gross_amount', 'net_amount', 'status'];
$order = in_array($filters['order'], $allowedColumns) ? $filters['order'] : 'created_at';
$sort = strtoupper($filters['sort']) === 'ASC' ? 'ASC' : 'DESC';
$query .= " ORDER BY s.$order $sort LIMIT 100";

$payments = $db->fetchAll($query, $params);

// Calculate totals
$totalPaid = array_sum(array_map(fn($p) => $p['net_amount'] ?? 0, array_filter($payments, fn($p) => $p['status'] === 'Paid')));
$totalPending = array_sum(array_map(fn($p) => $p['amount'] ?? 0, array_filter($payments, fn($p) => $p['status'] === 'pending')));

require_once __DIR__ . '/../../layouts/header.php';
?>

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Header -->
    <div class="mb-8">
        <div class="bg-gradient-to-r from-green-600 to-green-700 rounded-lg p-8 text-white shadow-lg">
            <h1 class="text-4xl font-bold">
                <i class="fas fa-money-bill mr-3"></i>Salary & Payments
            </h1>
            <p class="text-green-100 mt-2">View your payment history and salary information</p>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <!-- Total Paid -->
        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl shadow-lg text-white p-8">
            <div class="flex items-start justify-between mb-4">
                <div>
                    <p class="text-green-100 text-sm font-semibold uppercase tracking-wide">Total Paid</p>
                    <p class="text-4xl font-bold mt-2">FCFA <?php echo number_format($totalPaid, 2); ?></p>
                </div>
                <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                    <i class="fas fa-check-circle text-3xl"></i>
                </div>
            </div>
            <p class="text-green-200 text-sm">All completed payments</p>
        </div>

        <!-- Pending Payments -->
        <div class="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-xl shadow-lg text-white p-8">
            <div class="flex items-start justify-between mb-4">
                <div>
                    <p class="text-yellow-100 text-sm font-semibold uppercase tracking-wide">Pending</p>
                    <p class="text-4xl font-bold mt-2">FCFA <?php echo number_format($totalPending, 2); ?></p>
                </div>
                <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                    <i class="fas fa-hourglass-half text-3xl"></i>
                </div>
            </div>
            <p class="text-yellow-200 text-sm">Awaiting processing</p>
        </div>

        <!-- Total Payments -->
        <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shadow-lg text-white p-8">
            <div class="flex items-start justify-between mb-4">
                <div>
                    <p class="text-blue-100 text-sm font-semibold uppercase tracking-wide">Total Records</p>
                    <p class="text-4xl font-bold mt-2"><?php echo count($payments); ?></p>
                </div>
                <div class="w-16 h-16 bg-white bg-opacity-20 rounded-full flex items-center justify-center">
                    <i class="fas fa-receipt text-3xl"></i>
                </div>
            </div>
            <p class="text-blue-200 text-sm">Payment records</p>
        </div>
    </div>

    <!-- Current Salary Info -->
    <?php if ($salary): ?>
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-8 mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-file-contract text-green-600 mr-2"></i>Current Salary Information
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <!-- Basic Salary -->
                <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-6 border border-green-200">
                    <p class="text-sm font-bold text-gray-600 uppercase">Basic Salary</p>
                    <p class="text-3xl font-bold text-green-600 mt-2">FCFA <?php echo number_format($salary['basic_salary'] ?? 0, 2); ?></p>
                </div>

                <!-- Gross Amount -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-6 border border-blue-200">
                    <p class="text-sm font-bold text-gray-600 uppercase">Gross Amount</p>
                    <p class="text-3xl font-bold text-blue-600 mt-2">FCFA <?php echo number_format($salary['gross_amount'] ?? 0, 2); ?></p>
                </div>

                <!-- Allowances -->
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-6 border border-purple-200">
                    <p class="text-sm font-bold text-gray-600 uppercase">Allowances</p>
                    <p class="text-3xl font-bold text-purple-600 mt-2">FCFA <?php echo number_format($salary['allowances'] ?? 0, 2); ?></p>
                </div>

                <!-- Salary Month -->
                <div class="bg-gradient-to-br from-gray-50 to-gray-100 rounded-lg p-6 border border-gray-200">
                    <p class="text-sm font-bold text-gray-600 uppercase">Salary Month</p>
                    <p class="text-lg font-bold text-gray-800 mt-2">
                        <?php echo htmlspecialchars($salary['salary_month'] ?? date('Y-m')); ?>
                    </p>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Filters and Search -->
    <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-6 mb-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Search -->
            <div class="md:col-span-2">
                <form method="GET" class="flex gap-2">
                    <input type="hidden" name="page" value="guards-payments">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>" placeholder="Search payments..." class="flex-1 px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                    <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-semibold">
                        <i class="fas fa-search mr-2"></i>Search
                    </button>
                </form>
            </div>

            <!-- Sort -->
            <div>
                <form method="GET" class="flex gap-2" id="sortForm">
                    <input type="hidden" name="page" value="guards-payments">
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>">
                    <select name="order" onchange="document.getElementById('sortForm').submit()" class="flex-1 px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                        <option value="created_at" <?php echo $filters['order'] === 'created_at' ? 'selected' : ''; ?>>Date</option>
                        <option value="gross_amount" <?php echo $filters['order'] === 'gross_amount' ? 'selected' : ''; ?>>Amount</option>
                        <option value="status" <?php echo $filters['order'] === 'status' ? 'selected' : ''; ?>>Status</option>
                    </select>
                </form>
            </div>

            <!-- Direction -->
            <div>
                <form method="GET" id="directionForm">
                    <input type="hidden" name="page" value="guards-payments">
                    <input type="hidden" name="order" value="<?php echo htmlspecialchars($filters['order']); ?>">
                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($filters['search']); ?>">
                    <select name="sort" onchange="document.getElementById('directionForm').submit()" class="w-full px-4 py-2 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-green-500 transition">
                        <option value="desc" <?php echo $filters['sort'] === 'desc' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="asc" <?php echo $filters['sort'] === 'asc' ? 'selected' : ''; ?>>Oldest First</option>
                    </select>
                </form>
            </div>
        </div>
    </div>

    <!-- Payments Table -->
    <?php if (!empty($payments)): ?>
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-600 uppercase">Date</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-600 uppercase">Reference</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-600 uppercase">Description</th>
                            <th class="px-6 py-4 text-right text-xs font-bold text-gray-600 uppercase">Amount</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-600 uppercase">Status</th>
                            <th class="px-6 py-4 text-center text-xs font-bold text-gray-600 uppercase">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php foreach ($payments as $payment): 
                            $statusClass = match($payment['status']) {
                                'Paid' => 'bg-green-100 text-green-900',
                                'Approved' => 'bg-blue-100 text-blue-900',
                                'Draft' => 'bg-yellow-100 text-yellow-900',
                                'Cancelled' => 'bg-red-100 text-red-900',
                                default => 'bg-gray-100 text-gray-900'
                            };
                            
                            $statusIcon = match($payment['status']) {
                                'Paid' => 'fa-check-circle',
                                'Approved' => 'fa-thumbs-up',
                                'Draft' => 'fa-hourglass-half',
                                'Cancelled' => 'fa-times-circle',
                                default => 'fa-question-circle'
                            };
                        ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="px-6 py-4 text-gray-800 font-medium">
                                    <?php echo date('M d, Y', strtotime($payment['created_at'])); ?>
                                </td>
                                <td class="px-6 py-4 text-gray-800 font-semibold">
                                    <?php echo htmlspecialchars($payment['salary_month'] ?? '-'); ?>
                                </td>
                                <td class="px-6 py-4 text-gray-700">
                                    <?php echo htmlspecialchars($payment['notes'] ?? 'Salary Record'); ?>
                                </td>
                                <td class="px-6 py-4 text-right text-gray-800 font-bold">
                                    FCFA <?php echo number_format($payment['net_amount'] ?? 0, 2); ?>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center gap-2 px-4 py-2 <?php echo $statusClass; ?> rounded-full text-xs font-bold">
                                        <i class="fas <?php echo $statusIcon; ?>"></i>
                                        <?php echo ucfirst($payment['status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-center">
                                    <button onclick="viewPaymentDetails(<?php echo htmlspecialchars(json_encode($payment)); ?>)" class="text-green-600 hover:text-green-900 font-semibold transition">
                                        <i class="fas fa-eye mr-1"></i>View
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-xl shadow-lg border border-gray-200 p-12 text-center">
            <i class="fas fa-money-bill text-5xl text-gray-300 mb-4"></i>
            <p class="text-gray-600 font-medium text-lg">No payment records found</p>
            <p class="text-gray-500 text-sm mt-2">Payment records will appear here once available</p>
        </div>
    <?php endif; ?>
</div>

<!-- Payment Details Modal -->
<div id="paymentModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <!-- Header -->
        <div class="sticky top-0 bg-gradient-to-r from-green-600 to-green-700 text-white p-6 flex items-center justify-between">
            <h2 class="text-2xl font-bold">Payment Details</h2>
            <button onclick="closePaymentModal()" class="text-white hover:bg-green-800 rounded-full p-3 transition">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>

        <!-- Content -->
        <div id="paymentContent" class="p-8 space-y-6">
            <!-- Loading -->
            <div class="text-center py-8">
                <i class="fas fa-spinner fa-spin text-green-600 text-3xl"></i>
            </div>
        </div>

        <!-- Footer -->
        <div class="sticky bottom-0 bg-gray-50 border-t border-gray-200 p-6 flex gap-3 justify-end">
            <button onclick="closePaymentModal()" class="px-6 py-2 text-gray-700 bg-white border-2 border-gray-300 rounded-lg hover:bg-gray-100 transition font-semibold">
                Close
            </button>
            <button onclick="downloadPaymentReceipt()" class="px-6 py-2 text-white bg-green-600 rounded-lg hover:bg-green-700 transition font-semibold flex items-center gap-2">
                <i class="fas fa-download"></i>Download
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let currentPayment = null;

function viewPaymentDetails(payment) {
    currentPayment = payment;
    const modal = document.getElementById('paymentModal');
    const content = document.getElementById('paymentContent');
    
    modal.classList.remove('hidden');
    
    const statusColors = {
        'completed': { bg: 'bg-green-100', text: 'text-green-900', icon: 'fa-check-circle' },
        'pending': { bg: 'bg-yellow-100', text: 'text-yellow-900', icon: 'fa-hourglass-half' },
        'failed': { bg: 'bg-red-100', text: 'text-red-900', icon: 'fa-times-circle' }
    };
    
    const status = statusColors[payment.status] || statusColors['pending'];
    
    content.innerHTML = `
        <div class="space-y-6">
            <!-- Amount and Status -->
            <div class="flex items-start justify-between border-b pb-4">
                <div>
                    <p class="text-sm text-gray-600 font-bold uppercase">Payment Amount</p>
                    <p class="text-4xl font-bold text-green-600 mt-2">FCFA ${parseFloat(payment.net_amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p>
                </div>
                <span class="px-6 py-3 ${status.bg} ${status.text} rounded-lg font-bold flex items-center gap-2">
                    <i class="fas ${status.icon}"></i>${payment.status.toUpperCase()}
                </span>
            </div>

            <!-- Payment Details -->
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-1">Payment Date</p>
                    <p class="text-gray-800 font-semibold">${new Date(payment.payment_date).toLocaleDateString()}</p>
                </div>
                <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs font-bold text-gray-600 uppercase mb-1">Reference</p>
                    <p class="text-gray-800 font-semibold font-mono">${payment.reference || 'N/A'}</p>
                </div>
            </div>

            <!-- Description -->
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Description</p>
                <p class="text-gray-800">${payment.description || 'Salary Payment'}</p>
            </div>

            <!-- Payment Method -->
            ${payment.payment_method ? `
            <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-xs font-bold text-gray-600 uppercase mb-2">Payment Method</p>
                <p class="text-gray-800 font-semibold">${payment.payment_method}</p>
            </div>
            ` : ''}

            <!-- Notes -->
            ${payment.notes ? `
            <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
                <p class="text-xs font-bold text-blue-700 uppercase mb-2">Notes</p>
                <p class="text-blue-900">${payment.notes}</p>
            </div>
            ` : ''}
        </div>
    `;
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.add('hidden');
    currentPayment = null;
}

function downloadPaymentReceipt() {
    if (!currentPayment) return;
    
    const link = document.createElement('a');
    link.href = `?page=api&endpoint=guards/payment-receipt&payment_id=${currentPayment.id}`;
    link.download = `payment-${currentPayment.reference}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
