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

// Get Platform Earnings Stats
$statsQuery = mysqli_query($con, "SELECT 
    COALESCE(SUM(order_amount), 0) as total_gmv,
    COALESCE(SUM(platform_commission), 0) as total_commission,
    COALESCE(SUM(vendor_earning), 0) as total_vendor_earnings
    FROM vendor_earnings");
$stats = mysqli_fetch_array($statsQuery);

// Get Payout Requests
$payoutsQuery = mysqli_query($con, "SELECT vp.*, v.store_name, v.bank_name, v.bank_account_number 
                                    FROM vendor_payouts vp 
                                    JOIN vendors v ON vp.vendor_id = v.id 
                                    ORDER BY vp.requested_date DESC");

// Handle Payout Action
if (isset($_POST['process_payout'])) {
    $payoutId = intval($_POST['payout_id']);
    $action = $_POST['action']; // completed, failed
    $adminId = $_SESSION['id'];

    mysqli_query($con, "UPDATE vendor_payouts SET status='$action', processed_date=NOW() WHERE id='$payoutId'");

    // If failed, return money to vendor pending balance? (Logic can be added later)
    // For now, we assume simple status tracking

    $_SESSION['msg'] = "Payout marked as " . $action;
    header('location: vendor-earnings.php');
    exit;
}
?>

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

<head>
    <meta charset="utf-8" />
    <title>Vendor Earnings & Payouts - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="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-money-check-alt me-2"></i> Financials</h1>
                            <p>Monitor platform revenue and vendor payouts</p>
                        </div>
                    </div>

                    <?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; ?>

                    <!-- Platform Stats -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="stat-card">
                                <div class="stat-icon primary"><i class="fas fa-globe"></i></div>
                                <div class="stat-value">₵
                                    <?php echo number_format($stats['total_gmv'], 2); ?>
                                </div>
                                <div class="stat-label">Total Volume (GMV)</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card">
                                <div class="stat-icon success"><i class="fas fa-hand-holding-usd"></i></div>
                                <div class="stat-value">₵
                                    <?php echo number_format($stats['total_commission'], 2); ?>
                                </div>
                                <div class="stat-label">Platform Revenue (Commission)</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card">
                                <div class="stat-icon info"><i class="fas fa-users"></i></div>
                                <div class="stat-value">₵
                                    <?php echo number_format($stats['total_vendor_earnings'], 2); ?>
                                </div>
                                <div class="stat-label">Total Vendor Earnings</div>
                            </div>
                        </div>
                    </div>

                    <!-- Payouts Table -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0">Payout Requests</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-hover" id="datatablesSimple">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Vendor</th>
                                        <th>Amount</th>
                                        <th>Method</th>
                                        <th>Bank Details</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($payout = mysqli_fetch_array($payoutsQuery)) {
                                        $statusClass = 'warning';
                                        if ($payout['status'] == 'completed')
                                            $statusClass = 'success';
                                        elseif ($payout['status'] == 'failed' || $payout['status'] == 'cancelled')
                                            $statusClass = 'danger';
                                        ?>
                                        <tr>
                                            <td>#
                                                <?php echo $payout['id']; ?>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($payout['store_name']); ?>
                                            </td>
                                            <td><strong>₵
                                                    <?php echo number_format($payout['amount'], 2); ?>
                                                </strong></td>
                                            <td>
                                                <?php echo ucwords(str_replace('_', ' ', $payout['payout_method'])); ?>
                                            </td>
                                            <td>
                                                <small>
                                                    <?php if ($payout['payout_method'] == 'bank_transfer'): ?>
                                                        <?php echo htmlentities($payout['bank_name']); ?> /
                                                        <?php echo htmlentities($payout['bank_account_number']); ?>
                                                    <?php else: ?>
                                                        N/A
                                                    <?php endif; ?>
                                                </small>
                                            </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>
                                            <td>
                                                <?php if ($payout['status'] == 'pending'): ?>
                                                    <form method="post" class="d-inline">
                                                        <input type="hidden" name="payout_id"
                                                            value="<?php echo $payout['id']; ?>">
                                                        <button type="submit" name="action" value="completed"
                                                            class="btn btn-sm btn-success"
                                                            onclick="return confirm('Mark as Paid?');">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                        <button type="submit" name="action" value="failed"
                                                            class="btn btn-sm btn-danger"
                                                            onclick="return confirm('Mark as Failed?');">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>