<?= $this->extend('tipster/layout') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">
            <i class="bi bi-cash-stack me-2"></i>Sales & Earnings
        </h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <?php if ($availableBalance >= 20000): ?>
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#withdrawModal">
                    <i class="bi bi-wallet2 me-2"></i>Withdraw
                </button>
            <?php else: ?>
                <button type="button" class="btn btn-success" disabled title="Minimum withdrawal is 20,000 UGX">
                    <i class="bi bi-wallet2 me-2"></i>Withdraw
                </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- Sales Summary Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card border-left-primary">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-2">Total Sales (7 days)</h6>
                            <h4 class="mb-0"><?= number_format($settlementSummary['total_amount'], 2) ?> UGX</h4>
                            <small class="text-muted"><?= $settlementSummary['total_sales'] ?> sales</small>
                        </div>
                        <div class="text-primary" style="font-size: 2.5rem;">
                            <i class="bi bi-bar-chart"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-success">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-2">Settled</h6>
                            <h4 class="mb-0"><?= number_format($settlementSummary['settled_amount'], 2) ?> UGX</h4>
                            <small class="text-muted"><?= $settlementSummary['settled_count'] ?> sales</small>
                        </div>
                        <div class="text-success" style="font-size: 2.5rem;">
                            <i class="bi bi-check-circle"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-warning">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-2">Unsettled</h6>
                            <h4 class="mb-0"><?= number_format($settlementSummary['unsettled_amount'], 2) ?> UGX</h4>
                            <small class="text-muted"><?= $settlementSummary['unsettled_count'] ?> sales</small>
                        </div>
                        <div class="text-warning" style="font-size: 2.5rem;">
                            <i class="bi bi-clock-history"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-left-info">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-muted mb-2">Available Balance</h6>
                            <h4 class="mb-0 text-success"><?= number_format($availableBalance, 2) ?> UGX</h4>
                            <small class="text-muted">60% of unsettled</small>
                        </div>
                        <div class="text-info" style="font-size: 2.5rem;">
                            <i class="bi bi-wallet"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Sales List -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i>Sales History (Last 7 Days)</h5>
        </div>
        <div class="card-body">
            <?php if (empty($sales)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i>
                    <p class="text-muted mt-3">No sales found for the last 7 days</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Tip ID</th>
                                <th>Amount</th>
                                <th>Your Share (60%)</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Tag</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sales as $sale): ?>
                                <tr>
                                    <td>
                                        <span class="badge bg-primary">#<?= esc($sale['tip_id']) ?></span>
                                    </td>
                                    <td>
                                        <span class="fw-bold"><?= number_format($sale['amount'], 2) ?> UGX</span>
                                    </td>
                                    <td>
                                        <span class="fw-bold text-success"><?= number_format($sale['amount'] * 0.6, 2) ?> UGX</span>
                                    </td>
                                    <td>
                                        <?php if ($sale['is_settled']): ?>
                                            <span class="badge bg-success">
                                                <i class="bi bi-check-circle me-1"></i>Settled
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-warning">
                                                <i class="bi bi-clock me-1"></i>Pending
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= date('M d, Y H:i', strtotime($sale['created_at'])) ?></td>
                                    <td>
                                        <?php if (!empty($sale['tag'])): ?>
                                            <span class="badge bg-secondary"><?= esc($sale['tag']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Withdrawal History -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Withdrawal History</h5>
        </div>
        <div class="card-body">
            <?php if (empty($withdrawals)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i>
                    <p class="text-muted mt-3">No withdrawals yet</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Amount</th>
                                <th>Phone Number</th>
                                <th>Status</th>
                                <th>Reference</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($withdrawals as $withdrawal): ?>
                                <tr>
                                    <td><?= date('M d, Y H:i', strtotime($withdrawal['created_at'])) ?></td>
                                    <td>
                                        <span class="fw-bold"><?= number_format($withdrawal['amount'], 2) ?> <?= esc($withdrawal['currency']) ?></span>
                                    </td>
                                    <td>
                                        <span class="font-monospace"><?= esc($withdrawal['msisdn']) ?></span>
                                        <?php if (!empty($withdrawal['customer_name'])): ?>
                                            <br><small class="text-muted"><?= esc($withdrawal['customer_name']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                        $statusClass = [
                                            'success' => 'success',
                                            'pending' => 'warning',
                                            'failed' => 'danger'
                                        ];
                                        $statusIcon = [
                                            'success' => 'check-circle',
                                            'pending' => 'clock',
                                            'failed' => 'x-circle'
                                        ];
                                        $status = $withdrawal['status'];
                                        ?>
                                        <span class="badge bg-<?= $statusClass[$status] ?? 'secondary' ?>">
                                            <i class="bi bi-<?= $statusIcon[$status] ?? 'circle' ?> me-1"></i>
                                            <?= ucfirst($status) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($withdrawal['internal_reference'])): ?>
                                            <span class="font-monospace small"><?= esc($withdrawal['internal_reference']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                        <?php if (!empty($withdrawal['error_message'])): ?>
                                            <br><small class="text-danger"><?= esc($withdrawal['error_message']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Withdrawal Modal -->
<div class="modal fade" id="withdrawModal" tabindex="-1" aria-labelledby="withdrawModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="withdrawModalLabel">
                    <i class="bi bi-wallet2 me-2"></i>Withdraw Funds
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>Available Balance:</strong> <?= number_format($availableBalance, 2) ?> UGX<br>
                    <small>Minimum withdrawal: 20,000 UGX</small>
                </div>

                <form id="withdrawForm">
                    <div class="mb-3">
                        <label for="phoneNumber" class="form-label">Phone Number</label>
                        <div class="input-group">
                            <span class="input-group-text">+256</span>
                            <input type="text" class="form-control" id="phoneNumber" name="phoneNumber" 
                                   placeholder="7XXXXXXXX" maxlength="9" required>
                        </div>
                        <small class="form-text text-muted">Enter your phone number starting from 7</small>
                    </div>

                    <div class="mb-3">
                        <label for="amount" class="form-label">Amount (UGX)</label>
                        <input type="number" class="form-control" id="amount" name="amount" 
                               min="20000" max="<?= floor($availableBalance) ?>" step="1000" required>
                        <small class="form-text text-muted">Minimum: 20,000 UGX, Maximum: <?= number_format($availableBalance, 2) ?> UGX</small>
                    </div>

                    <div id="validationResult" class="mb-3" style="display: none;">
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle me-2"></i>
                            <strong>Validated:</strong> <span id="customerName"></span>
                        </div>
                    </div>

                    <input type="hidden" id="customerNameInput" name="customer_name">
                    <input type="hidden" id="validatedMsisdn" name="msisdn">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-info" id="validateBtn">
                    <i class="bi bi-check-circle me-2"></i>Validate
                </button>
                <button type="button" class="btn btn-success" id="confirmBtn" disabled>
                    <i class="bi bi-send me-2"></i>Confirm Withdrawal
                </button>
                <button type="button" class="btn btn-warning" id="resetBtn" style="display: none;">
                    <i class="bi bi-arrow-clockwise me-2"></i>Reset
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const withdrawModal = document.getElementById('withdrawModal');
    const withdrawForm = document.getElementById('withdrawForm');
    const phoneNumberInput = document.getElementById('phoneNumber');
    const amountInput = document.getElementById('amount');
    const validateBtn = document.getElementById('validateBtn');
    const confirmBtn = document.getElementById('confirmBtn');
    const resetBtn = document.getElementById('resetBtn');
    const validationResult = document.getElementById('validationResult');
    const customerNameSpan = document.getElementById('customerName');
    const customerNameInput = document.getElementById('customerNameInput');
    const validatedMsisdnInput = document.getElementById('validatedMsisdn');

    let isValidated = false;

    // Reset form when modal is closed
    withdrawModal.addEventListener('hidden.bs.modal', function() {
        resetForm();
    });

    // Validate button click
    validateBtn.addEventListener('click', function() {
        const phoneNumber = phoneNumberInput.value.trim();
        
        if (!phoneNumber || phoneNumber.length < 9) {
            alert('Please enter a valid phone number (9 digits starting with 7)');
            return;
        }

        const msisdn = '+256' + phoneNumber;
        validateBtn.disabled = true;
        validateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Validating...';

        fetch('<?= site_url('tipster/validate-phone') ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: 'msisdn=' + encodeURIComponent(msisdn)
        })
        .then(response => response.json())
        .then(data => {
            validateBtn.disabled = false;
            validateBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>Validate';

            if (data.success) {
                isValidated = true;
                customerNameSpan.textContent = data.customer_name || msisdn;
                customerNameInput.value = data.customer_name || '';
                validatedMsisdnInput.value = data.msisdn || msisdn;
                validationResult.style.display = 'block';
                confirmBtn.disabled = false;
                resetBtn.style.display = 'inline-block';
            } else {
                alert('Validation failed: ' + (data.message || 'Unknown error'));
                isValidated = false;
                validationResult.style.display = 'none';
                confirmBtn.disabled = true;
            }
        })
        .catch(error => {
            validateBtn.disabled = false;
            validateBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>Validate';
            alert('Error validating phone number: ' + error.message);
            isValidated = false;
        });
    });

    // Reset button click
    resetBtn.addEventListener('click', function() {
        resetForm();
    });

    // Confirm withdrawal
    confirmBtn.addEventListener('click', function() {
        if (!isValidated) {
            alert('Please validate your phone number first');
            return;
        }

        const amount = parseFloat(amountInput.value);
        const msisdn = validatedMsisdnInput.value;
        const customerName = customerNameInput.value;

        if (!amount || amount < 20000) {
            alert('Minimum withdrawal amount is 20,000 UGX');
            return;
        }

        if (!confirm('Confirm withdrawal of ' + amount.toLocaleString() + ' UGX to ' + msisdn + '?')) {
            return;
        }

        confirmBtn.disabled = true;
        confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';

        fetch('<?= site_url('tipster/withdraw') ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: 'msisdn=' + encodeURIComponent(msisdn) + 
                  '&amount=' + encodeURIComponent(amount) + 
                  '&customer_name=' + encodeURIComponent(customerName)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Withdrawal processed successfully!\nReference: ' + (data.internal_reference || 'N/A'));
                location.reload();
            } else {
                alert('Withdrawal failed: ' + (data.message || 'Unknown error'));
                confirmBtn.disabled = false;
                confirmBtn.innerHTML = '<i class="bi bi-send me-2"></i>Confirm Withdrawal';
            }
        })
        .catch(error => {
            alert('Error processing withdrawal: ' + error.message);
            confirmBtn.disabled = false;
            confirmBtn.innerHTML = '<i class="bi bi-send me-2"></i>Confirm Withdrawal';
        });
    });

    function resetForm() {
        phoneNumberInput.value = '';
        amountInput.value = '';
        isValidated = false;
        validationResult.style.display = 'none';
        customerNameInput.value = '';
        validatedMsisdnInput.value = '';
        confirmBtn.disabled = true;
        resetBtn.style.display = 'none';
        validateBtn.disabled = false;
    }
});
</script>

<style>
.border-left-primary {
    border-left: 4px solid #2563eb;
}
.border-left-success {
    border-left: 4px solid #059669;
}
.border-left-warning {
    border-left: 4px solid #d97706;
}
.border-left-info {
    border-left: 4px solid #0891b2;
}
</style>

<?= $this->endSection() ?>

