<?php
session_start();
require_once('../includes/vendor-security.php');
include_once('../../includes/config.php');

$vendorId = $_SESSION['vendor_id'];

// Handle payout request
if (isset($_POST['request_payout'])) {
    $amount = floatval($_POST['amount']);
    $method = mysqli_real_escape_string($con, $_POST['payout_method']);
    $notes = mysqli_real_escape_string($con, $_POST['notes']);

    // Check available balance
    $balanceQuery = mysqli_query($con, "SELECT COALESCE(SUM(vendor_earning), 0) as balance 
                                        FROM vendor_earnings 
                                        WHERE vendor_id='$vendorId' AND status='pending'");
    $balance = mysqli_fetch_assoc($balanceQuery)['balance'];

    if ($amount <= $balance && $amount > 0) {
        mysqli_query($con, "INSERT INTO vendor_payouts (vendor_id, amount, payout_method, notes, status) 
                           VALUES ('$vendorId', '$amount', '$method', '$notes', 'pending')");
        $_SESSION['msg'] = "Payout request submitted successfully!";
    } else {
        $_SESSION['error'] = "Invalid amount or insufficient balance!";
    }
    header('location: payouts.php');
    exit;
}

// Get available balance
$balanceQuery = mysqli_query($con, "SELECT COALESCE(SUM(vendor_earning), 0) as balance 
                                    FROM vendor_earnings 
                                    WHERE vendor_id='$vendorId' AND status='pending'");
$availableBalance = mysqli_fetch_assoc($balanceQuery)['balance'];

// Get payout history
$payoutsQuery = mysqli_query($con, "SELECT * FROM vendor_payouts 
                                    WHERE vendor_id='$vendorId' 
                                    ORDER BY requested_date DESC");

// Get vendor bank details
$vendorQuery = mysqli_query($con, "SELECT * FROM vendors WHERE id='$vendorId'");
$vendorDetails = mysqli_fetch_array($vendorQuery);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Payouts - Vendor Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="../../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../../__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('../includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('../includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-wallet me-2"></i> Payouts</h1>
                            <p>Request and manage your payouts</p>
                        </div>
                    </div>

                    <!-- Messages -->
                    <?php if (isset($_SESSION['msg'])): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Available Balance -->
                        <div class="col-lg-4 mb-4">
                            <div class="table-card">
                                <div class="card-header bg-success text-white">
                                    <h5 class="mb-0"><i class="fas fa-money-bill-wave me-2"></i>Available Balance</h5>
                                </div>
                                <div class="card-body text-center">
                                    <h2 class="text-success mb-3">₵
                                        <?php echo number_format($availableBalance, 2); ?>
                                    </h2>
                                    <button class="btn btn-success w-100" data-bs-toggle="modal"
                                        data-bs-target="#payoutModal" <?php echo ($availableBalance <= 0) ? 'disabled' : ''; ?>>
                                        <i class="fas fa-paper-plane me-2"></i>Request Payout
                                    </button>

                                    <?php if (!$vendorDetails['bank_account_number']): ?>
                                        <div class="alert alert-warning mt-3 mb-0">
                                            <small><i class="fas fa-exclamation-triangle me-1"></i>Add bank details in
                                                profile to receive payouts</small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Payout History -->
                        <div class="col-lg-8 mb-4">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-history me-2"></i>Payout History</h5>
                                </div>
                                <div class="card-body">
                                    <?php if (mysqli_num_rows($payoutsQuery) > 0): ?>
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                    <th>Status</th>
                                                    <th>Requested</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $cnt = 1;
                                                while ($payout = mysqli_fetch_array($payoutsQuery)) {
                                                    $statusClass = 'warning';
                                                    if ($payout['status'] == 'completed')
                                                        $statusClass = 'success';
                                                    elseif ($payout['status'] == 'processing')
                                                        $statusClass = 'info';
                                                    elseif ($payout['status'] == 'failed')
                                                        $statusClass = 'danger';
                                                    elseif ($payout['status'] == 'cancelled')
                                                        $statusClass = 'secondary';
                                                    ?>
                                                    <tr>
                                                        <td>
                                                            <?php echo $cnt; ?>
                                                        </td>
                                                        <td><strong>₵
                                                                <?php echo number_format($payout['amount'], 2); ?>
                                                            </strong></td>
                                                        <td>
                                                            <?php echo ucwords(str_replace('_', ' ', $payout['payout_method'])); ?>
                                                        </td>
                                                        <td><span class="badge bg-<?php echo $statusClass; ?>">
                                                                <?php echo ucfirst($payout['status']); ?>
                                                            </span></td>
                                                        <td>
                                                            <?php echo date('M d, Y', strtotime($payout['requested_date'])); ?>
                                                        </td>
                                                    </tr>
                                                    <?php
                                                    $cnt++;
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    <?php else: ?>
                                        <p class="text-muted text-center mb-0">No payout requests yet.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('../includes/footer.php'); ?>
        </div>
    </div>

    <!-- Payout Request Modal -->
    <div class="modal fade" id="payoutModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-wallet me-2"></i>Request Payout</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Amount to Withdraw (₵)</label>
                            <input type="number" name="amount" class="form-control" step="0.01"
                                max="<?php echo $availableBalance; ?>" required>
                            <small class="text-muted">Available: ₵
                                <?php echo number_format($availableBalance, 2); ?>
                            </small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Payout Method</label>
                            <select name="payout_method" class="form-select" required>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="mobile_money">Mobile Money</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Bank Details</label>
                            <div class="alert alert-info mb-0">
                                <?php if ($vendorDetails['bank_account_number']): ?>
                                    <strong>
                                        <?php echo htmlentities($vendorDetails['bank_name']); ?>
                                    </strong><br>
                                    Account:
                                    <?php echo htmlentities($vendorDetails['bank_account_number']); ?><br>
                                    Name:
                                    <?php echo htmlentities($vendorDetails['bank_account_name']); ?>
                                <?php else: ?>
                                    <small>No bank details on file. Please update your profile.</small>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes (Optional)</label>
                            <textarea name="notes" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="request_payout" class="btn btn-success">
                            <i class="fas fa-paper-plane me-2"></i>Submit Request
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../../__admin__/js/scripts.js"></script>
</body>

</html>