<?php
require_once '../app/Core/init.php';
// Require customer authentication
Auth::requireCustomer();


$user_id = Auth::id();
$db = Database::getInstance();

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filter
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';

// Build query
$where = "user_id = " . intval($user_id);
if ($status_filter !== 'all') {
    $where .= " AND status = '" . $db->escape($status_filter) . "'";
}

// Get total count
$count = $db->fetch("SELECT COUNT(*) as total FROM withdrawal_requests WHERE $where");
$total = $count ? intval($count['total']) : 0;
$total_pages = $total > 0 ? ceil($total / $per_page) : 1;

// Get withdrawals
$withdrawals = $db->fetchAll("SELECT * FROM withdrawal_requests WHERE $where ORDER BY created_at DESC LIMIT $per_page OFFSET $offset");
if (!$withdrawals) $withdrawals = [];

// Get ALL stats (not filtered)
$all_stats = $db->fetch("SELECT 
    COUNT(*) as total_requests,
    COALESCE(SUM(amount), 0) as total_amount,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
    COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) as pending_amount,
    SUM(CASE WHEN status IN ('approved', 'paid') THEN 1 ELSE 0 END) as approved_count,
    COALESCE(SUM(CASE WHEN status IN ('approved', 'paid') THEN amount ELSE 0 END), 0) as approved_amount,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_count,
    COALESCE(SUM(CASE WHEN status = 'rejected' THEN amount ELSE 0 END), 0) as rejected_amount
FROM withdrawal_requests WHERE user_id = " . intval($user_id));

// Set stats with defaults
$total_requests = $all_stats ? intval($all_stats['total_requests']) : 0;
$total_amount = $all_stats ? floatval($all_stats['total_amount']) : 0;
$pending_count = $all_stats ? intval($all_stats['pending_count']) : 0;
$pending_amount = $all_stats ? floatval($all_stats['pending_amount']) : 0;
$approved_count = $all_stats ? intval($all_stats['approved_count']) : 0;
$approved_amount = $all_stats ? floatval($all_stats['approved_amount']) : 0;
$rejected_count = $all_stats ? intval($all_stats['rejected_count']) : 0;
$rejected_amount = $all_stats ? floatval($all_stats['rejected_amount']) : 0;

$page_title = "Withdrawal History";
$active_menu = "withdrawals";
include '../templates/layouts/customer/head.php';
?>

<body class="fixed sidebar-mini">
<div class="wrapper">
    <nav class="sidebar">
        <div class="sidebar-header">
            <?php include '../templates/layouts/customer/navbar.php'; ?>
        </div>
    </nav>

    <div class="content-wrapper">
        <div class="main-content">
            <?php include '../templates/layouts/customer/header.php'; ?>
            
            <div class="page-header">
                <div class="page-title">
                    <h1>Withdrawal History</h1>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Withdrawals</li>
                    </ul>
                </div>
            </div>

            <div class="container-fluid">
                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-3 mb-3">
                        <div class="card text-white" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                            <div class="card-body">
                                <h6 class="mb-2">Total Requests</h6>
                                <h2 class="mb-0"><?php echo number_format($total_requests); ?></h2>
                                <small>₦<?php echo number_format($total_amount, 2); ?></small>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3 mb-3">
                        <div class="card text-white" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <div class="card-body">
                                <h6 class="mb-2">Pending</h6>
                                <h2 class="mb-0"><?php echo number_format($pending_count); ?></h2>
                                <small>₦<?php echo number_format($pending_amount, 2); ?></small>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3 mb-3">
                        <div class="card text-white" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                            <div class="card-body">
                                <h6 class="mb-2">Approved</h6>
                                <h2 class="mb-0"><?php echo number_format($approved_count); ?></h2>
                                <small>₦<?php echo number_format($approved_amount, 2); ?></small>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3 mb-3">
                        <div class="card text-white" style="background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);">
                            <div class="card-body">
                                <h6 class="mb-2">Rejected</h6>
                                <h2 class="mb-0"><?php echo number_format($rejected_count); ?></h2>
                                <small>₦<?php echo number_format($rejected_amount, 2); ?></small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="card shadow-sm">
                    <div class="card-header bg-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Withdrawal Requests</h5>
                            <a href="index.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-money-bill-wave"></i> New Withdrawal
                            </a>
                        </div>
                    </div>

                    <div class="card-header bg-light">
                        <ul class="nav nav-pills">
                            <li class="nav-item">
                                <a class="nav-link <?php echo $status_filter === 'all' ? 'active' : ''; ?>" href="?status=all">
                                    All (<?php echo $total_requests; ?>)
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $status_filter === 'pending' ? 'active' : ''; ?>" href="?status=pending">
                                    Pending (<?php echo $pending_count; ?>)
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $status_filter === 'approved' ? 'active' : ''; ?>" href="?status=approved">
                                    Approved (<?php echo $approved_count; ?>)
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $status_filter === 'rejected' ? 'active' : ''; ?>" href="?status=rejected">
                                    Rejected (<?php echo $rejected_count; ?>)
                                </a>
                            </li>
                        </ul>
                    </div>

                    <div class="card-body">
                        <?php if (empty($withdrawals)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted">No withdrawal requests found</h5>
                                <a href="index.php" class="btn btn-primary mt-3">
                                    <i class="fas fa-money-bill-wave"></i> Request Withdrawal
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Date</th>
                                            <th>Amount</th>
                                            <th>Bank Details</th>
                                            <th>Status</th>
                                            <th>Processed</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($withdrawals as $w): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo date('M d, Y', strtotime($w['created_at'])); ?></strong><br>
                                                    <small class="text-muted"><?php echo date('h:i A', strtotime($w['created_at'])); ?></small>
                                                </td>
                                                <td>
                                                    <h5 class="mb-0 fw-bold">₦<?php echo number_format($w['amount'], 2); ?></h5>
                                                </td>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($w['bank_name']); ?></strong><br>
                                                    <small class="text-muted">
                                                        <?php echo htmlspecialchars($w['account_number']); ?><br>
                                                        <?php echo htmlspecialchars($w['account_name']); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <?php
                                                    $badge = 'secondary';
                                                    $icon = 'question';
                                                    if ($w['status'] == 'pending') { $badge = 'warning'; $icon = 'clock'; }
                                                    if ($w['status'] == 'approved' || $w['status'] == 'paid') { $badge = 'success'; $icon = 'check-circle'; }
                                                    if ($w['status'] == 'rejected') { $badge = 'danger'; $icon = 'times-circle'; }
                                                    ?>
                                                    <span class="badge bg-<?php echo $badge; ?>">
                                                        <i class="fas fa-<?php echo $icon; ?>"></i> 
                                                        <?php echo ucfirst($w['status']); ?>
                                                    </span>
                                                    <?php if ($w['status'] == 'rejected' && !empty($w['rejection_reason'])): ?>
                                                        <br><small class="text-danger mt-1 d-block">
                                                            <i class="fas fa-info-circle"></i> 
                                                            <?php echo htmlspecialchars($w['rejection_reason']); ?>
                                                        </small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if (!empty($w['processed_at'])): ?>
                                                        <small class="text-muted">
                                                            <?php echo date('M d, Y', strtotime($w['processed_at'])); ?><br>
                                                            <?php echo date('h:i A', strtotime($w['processed_at'])); ?>
                                                        </small>
                                                    <?php else: ?>
                                                        <small class="text-muted">-</small>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <?php if ($total_pages > 1): ?>
                                <div class="mt-4">
                                    <nav>
                                        <ul class="pagination justify-content-center">
                                            <?php if ($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?status=<?php echo $status_filter; ?>&page=<?php echo ($page - 1); ?>">Previous</a>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = 1; $i <= min($total_pages, 10); $i++): ?>
                                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?status=<?php echo $status_filter; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                                </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?status=<?php echo $status_filter; ?>&page=<?php echo ($page + 1); ?>">Next</a>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php include '../templates/layouts/customer/footer.php'; ?>
    </div>
</div>
</body>
</html>