<?php
/**
 * CUSTOMER WALLET PAGE
 * File: customer/wallet.php
 * UPDATED WITH WalletStats V4.0
 */

require_once '../app/Core/init.php';
require_once '../app/Core/WalletStats.php';

// Require customer authentication
Auth::requireCustomer();

// Initialize models
$customerModel = new Customer();
$walletTransactionModel = new WalletTransaction();

// Get current user ID
$user_id = Auth::id();

// Get customer data
$customer_data = $customerModel->findByUserId($user_id);

if (!$customer_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('profile.php');
}

// ================================================================
// GET WALLET STATISTICS USING WalletStats
// ================================================================
$walletStats = new WalletStats();
$wallet_cards = $walletStats->getCustomerWalletCards($user_id);

// Ensure all values exist with defaults
$wallet_cards = array_merge([
    'available_balance' => 0.00,
    'withhold_deposit' => 0.00,
    'total_spent_lifetime' => 0.00,
    'total_spent_this_month' => 0.00,
    'total_withdrawn' => 0.00
], $wallet_cards);

// Pagination for transactions
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Get filters
$filter_type = $_GET['type'] ?? 'all';
$filter_date = $_GET['date'] ?? 'all';

// Build filter array for transactions
$filters = [];

if ($filter_type !== 'all') {
    $filters['transaction_type'] = $filter_type;
}

if ($filter_date !== 'all') {
    switch ($filter_date) {
        case 'today':
            $filters['date_from'] = date('Y-m-d');
            $filters['date_to'] = date('Y-m-d');
            break;
        case 'week':
            $filters['date_from'] = date('Y-m-d', strtotime('-7 days'));
            break;
        case 'month':
            $filters['date_from'] = date('Y-m-d', strtotime('-30 days'));
            break;
    }
}

// Get transactions using WalletStats
$transactions = $walletStats->getCustomerTransactions($user_id, $per_page, $offset);
$total_transactions = count($transactions); // For now, get accurate count from model if available

$total_pages = ceil($total_transactions / $per_page);

$page_title = "Wallet";
$active_menu = "wallet";

include '../templates/layouts/customer/head.php';
?>

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

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

    <!-- Wallet Overview - UPDATED WITH CORRECT METRICS -->
    <div class="row mb-4">
        <!-- Card 1: Available Balance -->
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2">Available Balance</h6>
                            <h2 class="mb-0">₦<?php echo number_format($wallet_cards['available_balance'], 2); ?></h2>
                            <small>Ready to use</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.3;">💰</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 2: Security Held -->
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-2">Security Held</h6>
                            <h2 class="mb-0">₦<?php echo number_format($wallet_cards['withhold_deposit'], 2); ?></h2>
                            <small>Active rentals</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.3;">🔒</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 3: Total Spent (Lifetime) -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Spent</h6>
                    <h3 class="mb-0">₦<?php echo number_format($wallet_cards['total_spent_lifetime'], 2); ?></h3>
                    <small class="text-muted">Lifetime</small>
                </div>
            </div>
        </div>

        <!-- Card 4: This Month -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Spent This Month</h6>
                    <h3 class="mb-0">₦<?php echo number_format($wallet_cards['total_spent_this_month'], 2); ?></h3>
                    <small class="text-muted"><?php echo date('F Y'); ?></small>
                </div>
            </div>
        </div>
    </div>

    <!-- Info Alert -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="alert alert-info">
                <h5><i class="fas fa-info-circle"></i> About Your Wallet</h5>
                <p class="mb-0">
                    <strong>Available Balance:</strong> Includes refunded security deposits and wallet top-ups. You can use this for future rentals or contact support to withdraw.<br>
                    <strong>Security Held:</strong> Total security deposits for your active rentals. These will be refunded when rentals are completed.<br>
                    <strong>Total Spent:</strong> Your actual rental spending (excludes security deposits).
                </p>
            </div>
        </div>
    </div>

    <!-- Security Deposits Held Details -->
    <?php if ($wallet_cards['withhold_deposit'] > 0): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Security Deposits Held (₦<?php echo number_format($wallet_cards['withhold_deposit'], 2); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php
                    $deposits = $walletStats->getCustomerSecurityDeposits($user_id);
                    if (!empty($deposits)):
                    ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Order</th>
                                    <th>Item</th>
                                    <th>Vendor</th>
                                    <th>Rental Period</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($deposits as $dep): ?>
                                <tr>
                                    <td>
                                        <a href="orders/view.php?order_number=<?php echo $dep['order_number']; ?>">
                                            <?php echo htmlspecialchars($dep['order_number']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($dep['item_name']); ?></td>
                                    <td><?php echo htmlspecialchars($dep['vendor_name']); ?></td>
                                    <td>
                                        <?php echo date('M d', strtotime($dep['start_date'])); ?> - 
                                        <?php echo date('M d, Y', strtotime($dep['end_date'])); ?>
                                    </td>
                                    <td>
                                        <strong>₦<?php echo number_format($dep['amount'], 2); ?></strong>
                                    </td>
                                    <td>
                                        <span class="badge badge-warning">
                                            <?php echo ucfirst($dep['order_status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Transaction History -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Transaction History</h5>
                </div>
                <div class="card-body">
                    <!-- Filters -->
                    <form method="GET" class="mb-3">
                        <div class="row">
                            <div class="col-md-6">
                                <select name="type" class="form-control" onchange="this.form.submit()">
                                    <option value="all">All Types</option>
                                    <option value="item_rental" <?php echo $filter_type === 'item_rental' ? 'selected' : ''; ?>>Rental Payments</option>
                                    <option value="security_deposit_held" <?php echo $filter_type === 'security_deposit_held' ? 'selected' : ''; ?>>Security Held</option>
                                    <option value="security_deposit_refund" <?php echo $filter_type === 'security_deposit_refund' ? 'selected' : ''; ?>>Security Refunds</option>
                                    <option value="rental_refund" <?php echo $filter_type === 'rental_refund' ? 'selected' : ''; ?>>Rental Refunds</option>
                                    <option value="top_up" <?php echo $filter_type === 'top_up' ? 'selected' : ''; ?>>Wallet Top-ups</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <select name="date" class="form-control" onchange="this.form.submit()">
                                    <option value="all">All Time</option>
                                    <option value="today" <?php echo $filter_date === 'today' ? 'selected' : ''; ?>>Today</option>
                                    <option value="week" <?php echo $filter_date === 'week' ? 'selected' : ''; ?>>Last 7 Days</option>
                                    <option value="month" <?php echo $filter_date === 'month' ? 'selected' : ''; ?>>Last 30 Days</option>
                                </select>
                            </div>
                        </div>
                    </form>

                    <!-- Transactions Table -->
                    <?php if (empty($transactions)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-receipt fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No transactions found</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Date & Time</th>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $txn): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></strong>
                                                <br>
                                                <small class="text-muted"><?php echo date('h:i A', strtotime($txn['created_at'])); ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $txn['category'] === 'credit' ? 'success' : 'warning'; ?>">
                                                    <?php echo $walletStats->getTransactionTypeLabel($txn['transaction_type']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($txn['description']); ?>
                                                <?php if (!empty($txn['order_number'])): ?>
                                                    <br>
                                                    <small class="text-muted">
                                                        Order: <a href="orders/view.php?order_number=<?php echo htmlspecialchars($txn['order_number']); ?>">
                                                            <?php echo htmlspecialchars($txn['order_number']); ?>
                                                        </a>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <strong class="<?php echo $txn['category'] === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                                    <?php echo $txn['category'] === 'credit' ? '+' : '-'; ?>
                                                    ₦<?php echo number_format($txn['amount'], 2); ?>
                                                </strong>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $txn['status'] === 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($txn['status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <nav>
                                <ul class="pagination justify-content-center">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&type=<?php echo $filter_type; ?>&date=<?php echo $filter_date; ?>">
                                                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="?page=<?php echo $i; ?>&type=<?php echo $filter_type; ?>&date=<?php echo $filter_date; ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>

                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&type=<?php echo $filter_type; ?>&date=<?php echo $filter_date; ?>">
                                                Next
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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