<?php
/**
 * @var object $commissions
 * @var string $employeeId
 * @var string $status
 * @var string $dateFrom
 * @var string $dateTo
 * @var float $totalPending
 * @var float $totalPaid
 * @var array $employees
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-coins me-2 text-gold"></i>Commissions</h5>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3 col-6">
        <div class="glass-card text-center py-3">
            <div class="fs-3 text-warning fw-bold"><?= currency($totalPending) ?></div>
            <div class="small text-muted">Total Pending</div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="glass-card text-center py-3">
            <div class="fs-3 text-success fw-bold"><?= currency($totalPaid) ?></div>
            <div class="small text-muted">Total Paid</div>
        </div>
    </div>
</div>

<div class="glass-card p-0">
    <div class="card-header">
        <div class="card-header-left">
            <i class="fas fa-list card-icon"></i>
            <h6 class="card-title">Commission Records</h6>
        </div>
        <div class="card-header-right">
            <?php if (can('commissions_create')): ?>
                <button type="button" class="btn btn-sm btn-gold" id="btnCalculate">
                    <i class="fas fa-calculator me-1"></i>Calculate Pending
                </button>
            <?php endif; ?>
        </div>
    </div>
    <div class="card-body">
        <div class="row mb-3">
            <div class="col-md-10">
                <form method="GET" action="<?= url('commissions') ?>" class="d-flex gap-2 flex-wrap">
                    <select name="employee_id" class="form-select form-select-sm bg-transparent" style="width:auto;">
                        <option value="">All Employees</option>
                        <?php foreach ($employees as $emp): ?>
                            <option value="<?= $emp->id ?>" <?= $employeeId == $emp->id ? 'selected' : '' ?>>
                                <?= e($emp->first_name . ' ' . $emp->last_name) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <select name="status" class="form-select form-select-sm bg-transparent" style="width:auto;">
                        <option value="">All Status</option>
                        <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="paid" <?= $status === 'paid' ? 'selected' : '' ?>>Paid</option>
                    </select>
                    <div class="input-group" style="width:auto;">
                        <span class="input-group-text bg-transparent border-gold">
                            <i class="fas fa-calendar-start text-gold"></i>
                        </span>
                        <input type="date" name="date_from" class="form-control form-control-sm bg-transparent"
                               value="<?= e($dateFrom) ?>">
                    </div>
                    <div class="input-group" style="width:auto;">
                        <span class="input-group-text bg-transparent border-gold">
                            <i class="fas fa-calendar-end text-gold"></i>
                        </span>
                        <input type="date" name="date_to" class="form-control form-control-sm bg-transparent"
                               value="<?= e($dateTo) ?>">
                    </div>
                    <button type="submit" class="btn btn-sm btn-gold">
                        <i class="fas fa-filter me-1"></i>Filter
                    </button>
                    <a href="<?= url('commissions') ?>" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-times"></i>
                    </a>
                </form>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0">
                <thead>
                    <tr>
                        <th width="50">#</th>
                        <th>Employee</th>
                        <th>Service</th>
                        <th>Invoice</th>
                        <th>Date</th>
                        <th class="text-end">Amount</th>
                        <th>Status</th>
                        <th>Paid At</th>
                        <th width="80" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($commissions->data)): ?>
                        <tr>
                            <td colspan="9" class="text-center text-muted py-4">
                                <i class="fas fa-coins fa-2x mb-2"></i>
                                <p class="mb-0">No commission records found</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php $i = ($commissions->currentPage - 1) * $commissions->perPage + 1; ?>
                        <?php foreach ($commissions->data as $comm): ?>
                            <tr>
                                <td><?= $i++ ?></td>
                                <td>
                                    <a href="<?= url('employees/show/' . $comm->employee_id) ?>" class="text-gold text-decoration-none">
                                        <strong><?= e($comm->first_name . ' ' . $comm->last_name) ?></strong>
                                    </a>
                                </td>
                                <td><?= e($comm->service_name ?? '-') ?></td>
                                <td><?= e($comm->invoice_number ?? '-') ?></td>
                                <td><?= formatDateTime($comm->created_at) ?></td>
                                <td class="text-end"><?= currency($comm->amount) ?></td>
                                <td>
                                    <span class="badge bg-<?= statusBadge($comm->status) ?>">
                                        <?= e(ucfirst($comm->status)) ?>
                                    </span>
                                </td>
                                <td><?= !empty($comm->paid_at) ? formatDateTime($comm->paid_at) : '-' ?></td>
                                <td class="text-center">
                                    <?php if ($comm->status === 'pending' && can('commissions_edit')): ?>
                                        <a href="<?= url('commissions/pay/' . $comm->id) ?>" class="btn btn-sm btn-outline-success"
                                           onclick="return confirm('Mark this commission as paid?')">
                                            <i class="fas fa-check"></i>
                                        </a>
                                    <?php else: ?>
                                        <span class="text-muted small">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($commissions->totalPages > 1): ?>
            <div class="card-footer d-flex justify-content-between align-items-center">
                <div class="text-muted small">
                    Showing <?= (($commissions->currentPage - 1) * $commissions->perPage) + 1 ?>
                    to <?= min($commissions->currentPage * $commissions->perPage, $commissions->total) ?>
                    of <?= $commissions->total ?> entries
                </div>
                <?= paginateLinks($commissions, url('commissions')) ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if (can('commissions_create')): ?>
<div class="modal fade" id="calculateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content bg-dark">
            <div class="modal-header border-secondary">
                <h5 class="modal-title"><i class="fas fa-calculator text-gold me-2"></i>Calculate Commissions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="calculateForm">
                    <?= csrf_field() ?>
                    <div class="mb-3">
                        <label class="form-label">Date From</label>
                        <input type="date" name="date_from" class="form-control bg-transparent"
                               value="<?= date('Y-m-01') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Date To</label>
                        <input type="date" name="date_to" class="form-control bg-transparent"
                               value="<?= date('Y-m-t') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Employee (optional)</label>
                        <select name="employee_id" class="form-select bg-transparent">
                            <option value="">All Employees</option>
                            <?php foreach ($employees as $emp): ?>
                                <option value="<?= $emp->id ?>"><?= e($emp->first_name . ' ' . $emp->last_name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
                <div id="calculateFeedback"></div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-gold" id="submitCalculate">
                    <i class="fas fa-calculator me-1"></i>Calculate
                </button>
            </div>
        </div>
    </div>
</div>

<?php $inlineScripts = <<<'EOS'
$('#btnCalculate').click(function() {
    new bootstrap.Modal($('#calculateModal')[0]).show();
});

$('#submitCalculate').click(function() {
    const btn = $(this);
    const feedback = $('#calculateFeedback');
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Calculating...');
    feedback.html('');

    $.ajax({
        url: '__URL__/commissions/calculate',
        method: 'POST',
        data: $('#calculateForm').serialize() + '&_csrf_token=' + encodeURIComponent($('meta[name="csrf-token"]').attr('content')),
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                feedback.html('<div class="alert alert-success mb-0">' + res.message + '</div>');
                setTimeout(function() { location.reload(); }, 1500);
            } else {
                feedback.html('<div class="alert alert-danger mb-0">' + (res.message || 'Failed to calculate') + '</div>');
                btn.prop('disabled', false).html('<i class="fas fa-calculator me-1"></i>Calculate');
            }
        },
        error: function(xhr) {
            const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Server error';
            feedback.html('<div class="alert alert-danger mb-0">' + msg + '</div>');
            btn.prop('disabled', false).html('<i class="fas fa-calculator me-1"></i>Calculate');
        }
    });
});
EOS;
$inlineScripts = str_replace('__URL__', rtrim(APP_URL, '/'), $inlineScripts);
?>
<?php endif; ?>
