<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];

$site_settings = get_site_settings($pdo);
$min_withdrawal = $site_settings['min_withdrawal'] ?? 1000;
$system_comm = $site_settings['system_commission'] ?? 0;
$allow_withdrawals = $site_settings['allow_withdrawals'] ?? 1;

// Get Withdrawable Balance
try {
    // Total Earned (Completed Transactions)
    $stmt = $pdo->prepare("SELECT SUM(amount) as gross_earned FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'completed'");
    $stmt->execute([$user_id]);
    $gross_earned = $stmt->fetch()['gross_earned'] ?? 0;
    
    // Net Earned
    $total_earned = $gross_earned * (1 - ($system_comm / 100));

    // Total Withdrawn (Completed + Pending)
    $stmt = $pdo->prepare("SELECT SUM(amount) as withdrawn FROM withdrawals WHERE user_id = ? AND status IN ('completed', 'pending')");
    $stmt->execute([$user_id]);
    $total_withdrawn = $stmt->fetch()['withdrawn'] ?? 0;

    $available_balance = $total_earned - $total_withdrawn;

    // Withdrawal History
    $stmt = $pdo->prepare("SELECT * FROM withdrawals WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    $withdrawals = $stmt->fetchAll();
    
    // Last Withdrawal for Autofill
    $last_w = $withdrawals[0] ?? null;

} catch (PDOException $e) {
    $available_balance = 0;
    $withdrawals = [];
}

$pageTitle = "Withdraw - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <title><?= $pageTitle ?></title>
    <?php include 'includes/head.php'; ?>
    <style>
        .balance-card {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 16px;
            padding: 32px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 10px 20px rgba(78, 115, 223, 0.2);
        }
        .balance-card::after {
            content: '';
            position: absolute;
            right: -50px;
            bottom: -50px;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }
        .withdraw-btn {
            background: white;
            color: #4e73df;
            border: none;
            padding: 12px 24px;
            border-radius: 30px;
            font-weight: 700;
            transition: all 0.3s ease;
        }
        .withdraw-btn:hover { background: #f8f9fc; transform: translateY(-2px); }
        .withdraw-btn:disabled { background: rgba(255, 255, 255, 0.5); cursor: not-allowed; }

        .method-card {
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.2s;
            padding: 16px;
            border-radius: 12px;
            background: #f8f9fa;
        }
        .method-card.active { border-color: #4e73df; background: #eff6ff; }
        .method-card input { display: none; }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Withdraw Funds</h6>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium"><a href="dashboard.php" class="hover-text-primary">Dashboard</a></li>
                    <li>-</li>
                    <li class="fw-medium">Withdraw</li>
                </ul>
            </div>

            <style>
                .premium-payout-card {
                    background: linear-gradient(135deg, #d9f7ef 0%, #bde7dc 100%);
                    border: 1px solid rgba(0,0,0,0.05);
                    position: relative;
                    overflow: hidden;
                    box-shadow: 0 10px 30px rgba(0,0,0,0.03);
                    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
                    min-height: 120px;
                }
                .premium-payout-card:hover { transform: translateY(-5px) scale(1.01); box-shadow: 0 20px 40px rgba(0,0,0,0.06); }
                .payout-icon-bg {
                    position: absolute;
                    right: -20px;
                    top: -20px;
                    font-size: 150px;
                    opacity: 0.05;
                    transform: rotate(-15deg);
                }
                .btn-glass {
                    background: rgba(255, 255, 255, 0.4);
                    backdrop-filter: blur(8px);
                    border: 1px solid rgba(255, 255, 255, 0.5);
                    color: #2b3a36;
                    transition: all 0.3s;
                }
                .btn-glass:hover { background: #4e73df; color: white; border-color: #4e73df; }
            </style>

            <?php if (!$allow_withdrawals): ?>
            <div class="card premium-payout-card mb-32 border-0" style="background: linear-gradient(135deg, #fff5f5 0%, #ffe3e3 100%);">
                <i class="ri-error-warning-line payout-icon-bg text-danger"></i>
                <div class="card-body p-24 text-center">
                    <iconify-icon icon="solar:settings-bold-duotone" class="text-6xl text-danger mb-16 d-inline-block" style="animation: pulse 2s infinite;"></iconify-icon>
                    <h4 class="fw-bold text-dark mb-12">Withdrawals Currently Disabled</h4>
                    <p class="text-muted mx-auto mb-0" style="max-width: 600px;">
                        The system is currently undergoing maintenance. Withdrawals have been temporarily paused. 
                        Your earnings are safe and you will be able to withdraw them as soon as the maintenance is complete.
                    </p>
                </div>
            </div>
            <?php endif; ?>

            <div class="card premium-payout-card radius-0 mb-32 border-0">
                <i class="ri-hand-coin-line payout-icon-bg"></i>
                <div class="card-body p-24">
                    <div class="row align-items-center">
                        <div class="col-lg-7">
                            <div class="d-flex align-items-center gap-16">
                                <div class="w-60-px h-60-px radius-12 d-flex justify-content-center align-items-center bg-white shadow-sm">
                                    <iconify-icon icon="solar:wallet-money-bold-duotone" class="text-3xl text-primary-600"></iconify-icon>
                                </div>
                                <div>
                                    <span class="text-secondary-light fw-bold text-xs text-uppercase tracking-wider">Withdrawable Earning</span>
                                    <h2 class="text-dark fw-bold mb-0 mt-4">TSH <?= number_format($available_balance, 2) ?></h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-5 mt-24 mt-lg-0">
                            <div class="d-flex flex-wrap align-items-center justify-content-lg-end gap-24">
                                <div class="text-lg-end">
                                    <span class="text-secondary-light text-xs d-block fw-medium">Minimum Limit</span>
                                    <span class="fw-bold text-dark h6 mb-0"><?= number_format($min_withdrawal) ?> TZS</span>
                                </div>
                                <button class="btn btn-primary radius-0 px-32 py-16 fw-bold shadow-lg h-100" data-bs-toggle="modal" data-bs-target="#withdrawModal" <?= ($available_balance < $min_withdrawal || !$allow_withdrawals) ? 'disabled' : '' ?>>
                                    <i class="ri-send-plane-fill me-8"></i> Request Payout
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Withdrawal History -->
            <div class="card">
                <div class="card-header border-bottom">
                    <h6 class="mb-0 fw-bold">Withdrawal History</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table mb-0">
                            <thead class="bg-base">
                                <tr>
                                    <th class="ps-24">ID</th>
                                    <th>Date</th>
                                    <th>Method</th>
                                    <th>Destination</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(!empty($withdrawals)): ?>
                                    <?php foreach($withdrawals as $w): ?>
                                    <tr>
                                        <td class="ps-24 fw-bold text-primary-600 text-xs" style="font-family:monospace;">
                                            <?= htmlspecialchars($w['withdrawal_id'] ?: 'WDR-'.str_pad($w['id'], 6, '0', STR_PAD_LEFT)) ?>
                                        </td>
                                        <td>
                                            <div class="d-flex flex-column text-sm">
                                                <span class="fw-medium"><?= date('d M, Y', strtotime($w['created_at'])) ?></span>
                                                <span class="text-secondary-light"><?= date('h:i A', strtotime($w['created_at'])) ?></span>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge <?= $w['method'] == 'Bank transfer' ? 'bg-info-focus text-info-main' : 'bg-primary-focus text-primary-main' ?>">
                                                <?= htmlspecialchars($w['method']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="text-sm fw-medium"><?= htmlspecialchars($w['network_or_bank']) ?></div>
                                            <div class="text-xs text-secondary-light"><?= htmlspecialchars($w['mobile_or_account']) ?> (<?= htmlspecialchars($w['account_holder_name']) ?>)</div>
                                        </td>
                                        <td class="fw-bold">TSH <?= number_format($w['amount']) ?></td>
                                        <td>
                                            <?php if($w['status'] == 'completed'): ?>
                                                <span class="bg-success-focus text-success-main px-12 py-4 rounded-pill fw-medium text-xs">Completed</span>
                                            <?php elseif($w['status'] == 'cancelled'): ?>
                                                <span class="bg-danger-focus text-danger-main px-12 py-4 rounded-pill fw-medium text-xs">Cancelled</span>
                                            <?php else: ?>
                                                <span class="bg-warning-focus text-warning-main px-12 py-4 rounded-pill fw-medium text-xs">Pending</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center py-24 text-secondary-light">No withdrawal requests yet.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Withdraw Modal -->
        <div class="modal fade" id="withdrawModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content radius-16">
                    <div class="modal-header border-bottom">
                        <h6 class="modal-title fw-bold">Request Withdrawal</h6>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form id="withdrawForm">
                        <div class="modal-body">
                            <div class="mb-20">
                                <label class="form-label fw-semibold">Amount to Withdraw (TSH)</label>
                                <input type="number" class="form-control" name="amount" min="<?= $min_withdrawal ?>" max="<?= $available_balance ?>" step="1" required placeholder="Enter amount" value="<?= floor($available_balance) ?>">
                                <div class="form-text mt-8">Max: <?= number_format($available_balance) ?> TSH | Min: <?= number_format($min_withdrawal) ?> TSH</div>
                            </div>

                            <label class="form-label fw-semibold">Withdrawal Method</label>
                            <div class="row g-3 mb-20">
                                <div class="col-6">
                                    <label class="method-card <?= (!$last_w || $last_w['method'] !== 'Bank transfer') ? 'active' : '' ?> text-center w-100" for="method_mobile">
                                        <input type="radio" name="method" id="method_mobile" value="Mobile Money" <?= (!$last_w || $last_w['method'] !== 'Bank transfer') ? 'checked' : '' ?>>
                                        <iconify-icon icon="solar:phone-outline" class="text-3xl mb-8"></iconify-icon>
                                        <div class="fw-bold text-sm">Mobile Money</div>
                                    </label>
                                </div>
                                <div class="col-6">
                                    <label class="method-card <?= ($last_w && $last_w['method'] === 'Bank transfer') ? 'active' : '' ?> text-center w-100" for="method_bank">
                                        <input type="radio" name="method" id="method_bank" value="Bank transfer" <?= ($last_w && $last_w['method'] === 'Bank transfer') ? 'checked' : '' ?>>
                                        <iconify-icon icon="solar:bank-outline" class="text-3xl mb-8"></iconify-icon>
                                        <div class="fw-bold text-sm">Bank transfer</div>
                                    </label>
                                </div>
                            </div>

                            <!-- Mobile Fields -->
                            <div id="mobileFields" style="<?= ($last_w && $last_w['method'] === 'Bank transfer') ? 'display:none;' : '' ?>">
                                <div class="mb-16">
                                    <label class="form-label text-sm fw-medium">Network</label>
                                    <select class="form-select" name="network">
                                        <?php 
                                        $networks = ['M-Pesa', 'Tigo Pesa', 'Airtel Money', 'HaloPesa'];
                                        foreach($networks as $net): 
                                            $selected = ($last_w && $last_w['method'] !== 'Bank transfer' && $last_w['network_or_bank'] === $net) ? 'selected' : '';
                                        ?>
                                            <option value="<?= $net ?>" <?= $selected ?>><?= $net ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="mb-16">
                                    <label class="form-label text-sm fw-medium">Mobile Number</label>
                                    <input type="text" class="form-control" name="mobile_number" placeholder="07xxxxxxxx" value="<?= ($last_w && $last_w['method'] !== 'Bank transfer') ? htmlspecialchars($last_w['mobile_or_account']) : '' ?>">
                                </div>
                            </div>

                            <!-- Bank Fields -->
                            <div id="bankFields" style="<?= ($last_w && $last_w['method'] === 'Bank transfer') ? '' : 'display:none;' ?>">
                                <div class="mb-16">
                                    <label class="form-label text-sm fw-medium">Bank Name</label>
                                    <select class="form-select" name="bank">
                                        <?php 
                                        $banks = ['CRDB Bank', 'NMB Bank', 'NBC Bank', 'Equity Bank'];
                                        foreach($banks as $bnk): 
                                            $selected = ($last_w && $last_w['method'] === 'Bank transfer' && $last_w['network_or_bank'] === $bnk) ? 'selected' : '';
                                        ?>
                                            <option value="<?= $bnk ?>" <?= $selected ?>><?= $bnk ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="mb-16">
                                    <label class="form-label text-sm fw-medium">Account Number</label>
                                    <input type="text" class="form-control" name="account_number" placeholder="Enter account number" value="<?= ($last_w && $last_w['method'] === 'Bank transfer') ? htmlspecialchars($last_w['mobile_or_account']) : '' ?>">
                                </div>
                            </div>

                            <div class="mb-0">
                                <label class="form-label text-sm fw-medium">Account Holder Name</label>
                                <input type="text" class="form-control" name="holder_name" required placeholder="Full name on account" oninput="this.value = this.value.toUpperCase()" value="<?= $last_w ? htmlspecialchars($last_w['account_holder_name']) : '' ?>">
                            </div>
                        </div>
                        <div class="modal-footer border-top">
                            <button type="button" class="btn btn-secondary radius-8" data-bs-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary radius-8" id="submitBtn">Submit Request</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        $(document).ready(function() {
            // Toggle Methods
            $('input[name="method"]').on('change', function() {
                $('.method-card').removeClass('active');
                $(this).closest('.method-card').addClass('active');
                
                if ($(this).val() === 'Bank transfer') {
                    $('#mobileFields').hide();
                    $('#bankFields').show();
                } else {
                    $('#mobileFields').show();
                    $('#bankFields').hide();
                }
            });

            // Handle Form
            $('#withdrawForm').on('submit', function(e) {
                e.preventDefault();
                const $btn = $('#submitBtn');
                $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Processing...');

                $.ajax({
                    url: 'app/withdraw.php',
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(res) {
                        if (res.success) {
                            Swal.fire({ icon: 'success', title: 'Success', text: res.message })
                            .then(() => location.reload());
                        } else {
                            Swal.fire({ icon: 'error', title: 'Error', text: res.message });
                            $btn.prop('disabled', false).text('Submit Request');
                        }
                    },
                    error: function() {
                        Swal.fire({ icon: 'error', title: 'Error', text: 'Server error. Please try again.' });
                        $btn.prop('disabled', false).text('Submit Request');
                    }
                });
            });
        });
    </script>
</body>
</html>


