<?php
define('SECURE_ACCESS', true);

$pageTitle = "Withdraw Payout";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// 1. Fetch User Designation details to get Minimum Payout Requirement
$min_payout_amount = 10.00; // default backup fallback
$designation_title = 'None';
try {
    $stmt_desig = $pdo->prepare("
        SELECT d.title, d.criteria_min_payout 
        FROM users u 
        LEFT JOIN designations d ON u.designation_id = d.id 
        WHERE u.id = ?
    ");
    $stmt_desig->execute([$currentUser['id']]);
    $desig_info = $stmt_desig->fetch();
    if ($desig_info && $desig_info['title']) {
        $designation_title = $desig_info['title'];
        $min_payout_amount = (float)$desig_info['criteria_min_payout'];
    }
} catch (PDOException $e) {
    // Ignore
}

// 2. Fetch KYC status
$isKycVerified = false;
$kycRecord = null;
try {
    $stmt_kyc = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt_kyc->execute([$currentUser['id']]);
    $kycRecord = $stmt_kyc->fetch();
    if ($kycRecord && $kycRecord['doc1_status'] === 'approved' && $kycRecord['doc2_status'] === 'approved' && $kycRecord['bank_status'] === 'verified') {
        $isKycVerified = true;
    }
} catch (PDOException $e) {
    // Ignore
}

// 3. Load Configurations
$configs = [];
try {
    $stmt_config = $pdo->query("SELECT key, value FROM system_settings");
    $configs = $stmt_config->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
} catch (PDOException $e) {}

// 3.5 Compute Available Balance
// Available Balance = Sum(earnings.amount) - Sum(payouts.amount where status IN ('pending', 'paid'))
$total_earnings = 0.00;
$total_withdrawn = 0.00;
$available_balance = 0.00;
try {
    $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
    $stmt_earn->execute([$currentUser['id']]);
    $total_earnings = (float)$stmt_earn->fetchColumn();

    $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
    $stmt_pay->execute([$currentUser['id']]);
    $total_withdrawn = (float)$stmt_pay->fetchColumn();

    $available_balance = max(0.00, $total_earnings - $total_withdrawn);
} catch (PDOException $e) {
    $error = "Failed to calculate balances: " . $e->getMessage();
}

// 3.8 Check if user already requested a payout this month
$has_payout_this_month = false;
try {
    $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM payouts WHERE user_id = ? AND MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())");
    $stmt_check->execute([$currentUser['id']]);
    $has_payout_this_month = (int)$stmt_check->fetchColumn() > 0;
} catch (PDOException $e) {
    // Ignore
}

// 4. Handle Payout Request Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_payout'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: payouts");
        exit();
    }
    $amount = (float)($_POST['amount'] ?? 0.00);

    $platform_fee_pct = (float)($configs['payout_platform_fee'] ?? 5.00);
    $tds_with_pan_pct = (float)($configs['payout_tds_with_pan'] ?? 5.00);
    $tds_without_pan_pct = (float)($configs['payout_tds_without_pan'] ?? 20.00);

    $has_pan = ($kycRecord && !empty($kycRecord['doc2_number']) && $kycRecord['doc2_status'] === 'approved');
    $tds_pct = $has_pan ? $tds_with_pan_pct : $tds_without_pan_pct;

    $platform_fee = round($amount * ($platform_fee_pct / 100), 2);
    $tds_amount = round($amount * ($tds_pct / 100), 2);
    $net_amount = max(0.00, $amount - $platform_fee - $tds_amount);

    if (!$isKycVerified) {
        $error = "Withdrawal rejected: Your KYC documents must be approved and your bank account verified before requesting a payout.";
    } elseif ($has_payout_this_month) {
        $error = "Withdrawal rejected: You have already requested an advance payout this month. Your remaining balance will be processed automatically on the last day of the month.";
    } elseif ($amount <= 0.00) {
        $error = "Withdrawal rejected: Payout request amount must be greater than ₹0.00.";
    } elseif ($amount < $min_payout_amount) {
        $error = "Withdrawal rejected: Payout amount is below your designation (" . htmlspecialchars($designation_title) . ") minimum limit of ₹" . number_format($min_payout_amount, 2) . ".";
    } elseif ($amount > $available_balance) {
        $error = "Withdrawal rejected: Insufficient balance. You can withdraw up to ₹" . number_format($available_balance, 2) . ".";
    } else {
        try {
            $pdo->beginTransaction();
            
            // Lock the user row to serialize withdrawals for this user
            $stmt_lock = $pdo->prepare("SELECT id FROM users WHERE id = ? FOR UPDATE");
            $stmt_lock->execute([$currentUser['id']]);
            
            // Re-calculate balance inside the locked transaction
            $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
            $stmt_earn->execute([$currentUser['id']]);
            $total_earnings_lock = (float)$stmt_earn->fetchColumn();

            $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
            $stmt_pay->execute([$currentUser['id']]);
            $total_withdrawn_lock = (float)$stmt_pay->fetchColumn();

            $available_balance_lock = max(0.00, $total_earnings_lock - $total_withdrawn_lock);
            
            if ($amount > $available_balance_lock) {
                $error = "Withdrawal rejected: Insufficient balance. You can withdraw up to ₹" . number_format($available_balance_lock, 2) . ".";
                $pdo->rollBack();
            } else {
                // Log payout request
                $stmt_ins = $pdo->prepare("
                    INSERT INTO payouts (user_id, amount, platform_fee, tds_amount, net_amount, status, bank_name, account_number) 
                    VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)
                ");
                $stmt_ins->execute([
                    $currentUser['id'],
                    $amount,
                    $platform_fee,
                    $tds_amount,
                    $net_amount,
                    $kycRecord['bank_name'] ?? 'N/A',
                    $kycRecord['account_number'] ?? 'N/A'
                ]);
                
                $pdo->commit();
                
                // Trigger automated multichannel notification
                require_once __DIR__ . '/../includes/notification_helper.php';
                sendMultichannelNotification($currentUser['id'], 'payout_status', [
                    'amount' => number_format($amount, 2),
                    'status' => 'Pending Review'
                ]);
                
                $_SESSION['flash_success'] = "Payout request of ₹" . number_format($amount, 2) . " submitted successfully and is pending administrator approval.";
                header("Location: payouts");
                exit();
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = "Failed to save payout request: " . $e->getMessage();
        }
    }
}

// 5. Fetch Payout History
$payouts_history = [];
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;

try {
    if ($pdo) {
        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM payouts WHERE user_id = ?");
        $stmt_count->execute([$currentUser['id']]);
        $total_records = (int)$stmt_count->fetchColumn() ?: 0;
        $total_pages = ceil($total_records / $limit);

        $stmt_hist = $pdo->prepare("SELECT * FROM payouts WHERE user_id = ? ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
        $stmt_hist->execute([$currentUser['id']]);
        $payouts_history = $stmt_hist->fetchAll();
    }
} catch (PDOException $e) {
    // Ignore
}

include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Payout Manager</h1>
        <p class="text-muted mb-0">Withdraw your referral incentives and track withdrawal history.</p>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Left Column: Balance Cards and Form -->
    <div class="col-12 col-lg-8">
        
        <!-- Balances Grid -->
        <div class="row g-3 mb-4">
            <!-- Available Balance -->
            <div class="col-12 col-md-6">
                <div class="card border-0 shadow-sm bg-primary text-white h-100">
                    <div class="card-body p-4">
                        <small class="text-white-50 font-monospace text-uppercase" style="font-size: 0.75rem;">Available For Withdrawal</small>
                        <h1 class="display-5 fw-bold my-2">₹<?php echo number_format($available_balance, 2); ?></h1>
                        <p class="small text-white-50 mb-0">Accumulated earnings minus active payout requests.</p>
                    </div>
                </div>
            </div>

            <!-- Total Earnings -->
            <div class="col-12 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body p-4 d-flex flex-column justify-content-between">
                        <div>
                            <small class="text-muted font-monospace text-uppercase" style="font-size: 0.75rem;">Total Lifetime Earnings</small>
                            <h2 class="fw-bold text-dark my-2">₹<?php echo number_format($total_earnings, 2); ?></h2>
                        </div>
                        <span class="text-muted small">Total commissions paid out to date: ₹<?php echo number_format($total_withdrawn, 2); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- KYC Checks & Request Payout Form -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-cash-coin me-2 text-primary"></i>Request Advance</h5>
            </div>
            <div class="card-body p-4">
                <?php if (!$isKycVerified): ?>
                    <div class="alert alert-warning border-0 p-4 mb-0" role="alert">
                        <h5 class="alert-heading fw-bold mb-2"><i class="bi bi-shield-exclamation me-1"></i> KYC Verification Required</h5>
                        <p class="mb-3">To maintain legal compliance and secure corporate payout distribution, you must submit your identification documents and verify your bank account details before creating payout requests.</p>
                        <a href="kyc" class="btn btn-warning fw-bold text-dark"><i class="bi bi-arrow-right-circle-fill me-1"></i> Complete KYC Verification</a>
                    </div>
                <?php else: ?>
                    <form method="POST" action="payouts">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="mb-3">
                            <label for="amount" class="form-label">Advance Amount (₹) <span class="text-danger">*</span></label>
                            <div class="input-group input-group-lg mb-2">
                                <span class="input-group-text bg-white border-end-0">₹</span>
                                <input type="number" step="0.01" min="<?php echo $min_payout_amount; ?>" max="<?php echo $available_balance; ?>" class="form-control border-start-0 ps-0" id="amount" name="amount" required placeholder="0.00">
                            </div>
                            <div class="form-text text-muted small mb-3">
                                Minimum withdrawal amount: <strong class="text-dark">₹<?php echo number_format($min_payout_amount, 2); ?></strong> (Set by rank: <strong><?php echo htmlspecialchars($designation_title); ?></strong>).
                            </div>
                            
                            <!-- Real-time Fee Estimation Box -->
                            <div id="fee-estimation-box" class="p-3 bg-light rounded border border-light-subtle mb-3 d-none">
                                <div class="d-flex justify-content-between mb-1 text-secondary small">
                                    <span>Platform Fee (<?php echo $platform_fee_pct; ?>%):</span>
                                    <span id="est-platform-fee">₹0.00</span>
                                </div>
                                <div class="d-flex justify-content-between mb-1 text-secondary small">
                                    <span>TDS Deduction (<?php echo $tds_pct; ?>%<?php echo $has_pan ? ' - PAN Link' : ' - No PAN'; ?>):</span>
                                    <span id="est-tds">₹0.00</span>
                                </div>
                                <hr class="my-2 border-secondary-subtle">
                                <div class="d-flex justify-content-between fw-bold text-dark small">
                                    <span>Estimated Net Payout:</span>
                                    <span id="est-net-amount" class="text-success">₹0.00</span>
                                </div>
                            </div>
                        </div>

                        <div class="p-3 bg-light rounded border border-light-subtle mb-4 small text-secondary">
                            <i class="bi bi-bank me-1 text-primary"></i> Fund transfer destination: <strong><?php echo htmlspecialchars($kycRecord['bank_name']); ?></strong> (Account ending in *<?php echo substr($kycRecord['account_number'], -4); ?>).
                        </div>

                        <div class="d-grid">
                            <button type="submit" name="request_payout" class="btn btn-primary btn-lg fw-bold py-2.5">
                                <i class="bi bi-arrow-up-right-circle me-1"></i> Request Advance
                            </button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- Payout History -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-clock-history me-2 text-primary"></i>Withdrawal History</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                            <tr>
                                <th class="ps-4">Request Date</th>
                                <th>Requested Amount</th>
                                <th>Platform Fee</th>
                                <th>TDS</th>
                                <th>Net Payout</th>
                                <th>Bank Destination</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payouts_history)): ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4 text-muted">
                                        <i class="bi bi-wallet2 fs-2 mb-2"></i>
                                        <p class="mb-0">No withdrawal requests found.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($payouts_history as $pay): ?>
                                    <tr>
                                        <td class="ps-4">
                                            <span class="text-muted small"><?php echo date('Y-m-d H:i', strtotime($pay['created_at'])); ?></span>
                                        </td>
                                        <td>
                                            <strong class="text-dark">₹<?php echo number_format($pay['amount'], 2); ?></strong>
                                        </td>
                                        <td>
                                            <span class="text-secondary small">₹<?php echo number_format($pay['platform_fee'] ?? 0.00, 2); ?></span>
                                        </td>
                                        <td>
                                            <span class="text-secondary small">₹<?php echo number_format($pay['tds_amount'] ?? 0.00, 2); ?></span>
                                        </td>
                                        <td>
                                            <strong class="text-success">₹<?php echo number_format($pay['net_amount'] ?? 0.00, 2); ?></strong>
                                        </td>
                                        <td>
                                            <span class="small text-secondary"><?php echo htmlspecialchars($pay['bank_name'] ?? 'N/A'); ?> (*<?php echo substr($pay['account_number'] ?? '0000', -4); ?>)</span>
                                            <?php if (!empty($pay['utr_number'])): ?>
                                                <div class="mt-0.5 small text-muted font-monospace" style="font-size: 0.75rem;">UTR: <?php echo htmlspecialchars($pay['utr_number']); ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge <?php 
                                                if ($pay['status'] === 'paid') echo 'bg-success';
                                                elseif ($pay['status'] === 'rejected') echo 'bg-danger';
                                                else echo 'bg-warning text-dark';
                                            ?> text-uppercase font-monospace text-xs"><?php echo $pay['status']; ?></span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php if ($total_pages > 1): ?>
                <div class="card-footer bg-light border-top py-3 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                    <div class="small text-secondary font-monospace">
                        Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> payouts
                    </div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0 align-items-center gap-1">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">First</a>
                            </li>
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                            </li>
                            <li class="page-item disabled mx-1">
                                <span class="text-secondary small fw-bold" style="font-size: 0.75rem;">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                            </li>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                            </li>
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>">Last</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>

    </div>

    <!-- Right Column: Rank Rules & Payout Limitations Info -->
    <div class="col-12 col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-info-circle me-2 text-primary"></i>Rank Limits Summary</h5>
            </div>
            <div class="card-body">
                <div class="mb-4 text-center">
                    <small class="text-muted uppercase font-monospace d-block mb-1">Your Designation Profile</small>
                    <span class="badge bg-primary text-uppercase px-3 py-2 fs-6 mb-2"><?php echo htmlspecialchars($designation_title); ?></span>
                </div>

                <div class="p-3 bg-light rounded border border-light-subtle mb-4">
                    <h6 class="fw-bold mb-2 small text-dark">Minimum Payout Requirement</h6>
                    <p class="text-secondary small mb-0">Your designation enforces a minimum withdrawable amount of <strong>₹<?php echo number_format($min_payout_amount, 2); ?></strong>. Withdrawals containing balances below this quota are withheld.</p>
                </div>

                <h6 class="fw-bold mb-3 text-secondary font-monospace uppercase" style="font-size: 0.75rem;">Standard Withdrawal Compliance</h6>
                <ul class="list-group list-group-flush mb-0 small text-secondary">
                    <li class="list-group-item px-0 py-2 d-flex align-items-start border-0">
                        <i class="bi bi-check-circle-fill text-success me-2 mt-0.5"></i>
                        <span>Must have photo ID checked by compliance admin.</span>
                    </li>
                    <li class="list-group-item px-0 py-2 d-flex align-items-start border-0">
                        <i class="bi bi-check-circle-fill text-success me-2 mt-0.5"></i>
                        <span>Address proof must correspond to bank statements.</span>
                    </li>
                    <li class="list-group-item px-0 py-2 d-flex align-items-start border-0">
                        <i class="bi bi-check-circle-fill text-success me-2 mt-0.5"></i>
                        <span>Bank accounts must be verified using the PayPal micro-deposits system.</span>
                    </li>
                    <li class="list-group-item px-0 py-2 d-flex align-items-start border-0">
                        <i class="bi bi-check-circle-fill text-success me-2 mt-0.5"></i>
                        <span>Payout amounts are cleared within 24-48 business hours.</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const amountInput = document.getElementById('amount');
    const estimationBox = document.getElementById('fee-estimation-box');
    const estPlatformFee = document.getElementById('est-platform-fee');
    const estTds = document.getElementById('est-tds');
    const estNetAmount = document.getElementById('est-net-amount');
    
    const platformFeePct = <?php echo $platform_fee_pct; ?>;
    const tdsPct = <?php echo $tds_pct; ?>;
    
    if (amountInput) {
        amountInput.addEventListener('input', function() {
            const val = parseFloat(amountInput.value) || 0;
            if (val > 0) {
                estimationBox.classList.remove('d-none');
                const platformFee = Math.round(val * (platformFeePct / 100) * 100) / 100;
                const tds = Math.round(val * (tdsPct / 100) * 100) / 100;
                const net = Math.max(0, val - platformFee - tds);
                
                estPlatformFee.textContent = '₹' + platformFee.toFixed(2);
                estTds.textContent = '₹' + tds.toFixed(2);
                estNetAmount.textContent = '₹' + net.toFixed(2);
            } else {
                estimationBox.classList.add('d-none');
            }
        });
    }
});
</script>

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