<?php
/**
 * VENDOR WALLET PAGE
 * File: vendor/wallet.php
 * UPDATED WITH NEW WALLET SYSTEM
 */

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

// Require vendor authentication
Auth::requireVendor();

// Initialize models
$vendorModel = new Vendor();
$walletModel = new Wallet();
$walletTransactionModel = new WalletTransaction();
$withdrawalModel = new Withdrawal();
$userModel = new User();

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

// Get vendor data
$vendor_data = $vendorModel->getByUserId($user_id);

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

// Get or create wallet
$wallet_data = $walletModel->findByUserId($user_id);

if (!$wallet_data) {
    $walletModel->create($user_id);
    $wallet_data = $walletModel->findByUserId($user_id);
}

// Get bank details from users table
$bank_details = $userModel->getBankDetails($user_id);

// Handle withdrawal request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'withdraw') {
    $amount = floatval($_POST['amount'] ?? 0);
    $bank_name = trim($_POST['bank_name'] ?? '');
    $account_number = trim($_POST['account_number'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    
    // Validate withdrawal
    $validation = WalletHelper::validateWithdrawalAmount($user_id, $amount);
    
    if (!$validation['valid']) {
        flash('error', $validation['message'], 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
    
    // Validate bank details
    if (empty($bank_name) || empty($account_number) || empty($account_name)) {
        flash('error', 'Please provide complete bank details', 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
    
    if (!WalletHelper::validateAccountNumber($account_number)) {
        flash('error', 'Invalid account number. Must be 10 digits', 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
    
    // Check for pending withdrawal
    if ($withdrawalModel->hasPendingWithdrawal($user_id)) {
        flash('error', 'You have a pending withdrawal request. Please wait for it to be processed.', 'warning');
        redirect($_SERVER['PHP_SELF']);
    }
    
    $db = Database::getInstance();
    $db->beginTransaction();
    
    try {
        // Generate reference
        $reference = $withdrawalModel->generateReference();
        
        // Create withdrawal request
        $withdrawal_id = $withdrawalModel->create([
            'user_id' => $user_id,
            'wallet_id' => $wallet_data['id'],
            'amount' => $amount,
            'bank_name' => $bank_name,
            'account_number' => $account_number,
            'account_name' => $account_name,
            'reference' => $reference
        ]);
        
        if (!$withdrawal_id) {
            throw new Exception("Failed to create withdrawal request");
        }
        
        // Debit wallet immediately
        $debit_success = $walletModel->debit(
            $user_id,
            $amount,
            'withdrawal',
            "Withdrawal request {$reference}",
            $reference
        );
        
        if (!$debit_success) {
            throw new Exception("Failed to debit wallet");
        }
        
        $db->commit();
        
        flash('success', 'Withdrawal request submitted successfully! Reference: ' . $reference, 'success');
        redirect($_SERVER['PHP_SELF']);
        
    } catch (Exception $e) {
        $db->rollback();
        flash('error', 'Failed to process withdrawal: ' . $e->getMessage(), 'danger');
        redirect($_SERVER['PHP_SELF']);
    }
}

// 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';

$filters = ['user_id' => $user_id];

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
$transactions = $walletTransactionModel->getAll($per_page, $offset, $filters);
$total_transactions = $walletTransactionModel->count($filters);
$total_pages = ceil($total_transactions / $per_page);

// Get wallet stats using WalletStats class (AFTER total_transactions is defined)
$walletStats = new WalletStats();
$wallet_stats = $walletStats->getVendorWalletCards($user_id);

// Format for display
$wallet_stats_display = [
    'balance' => WalletHelper::formatMoney($wallet_stats['available_balance']),
    'balance_raw' => $wallet_stats['available_balance'],
    'total_earned' => WalletHelper::formatMoney($wallet_stats['total_earned']),
    'total_earned_raw' => $wallet_stats['total_earned'],
    'total_withdrawn' => WalletHelper::formatMoney($wallet_stats['total_withdrawn']),
    'total_withdrawn_raw' => $wallet_stats['total_withdrawn'],
    'pending_earning' => WalletHelper::formatMoney($wallet_stats['pending_earning']),
    'pending_earning_raw' => $wallet_stats['pending_earning'],
    'total_transactions' => $total_transactions
];

// Get withdrawal history
$withdrawal_history = $withdrawalModel->getByUserId($user_id, 10);

$page_title = "Wallet";
include '../templates/layouts/vendor/header.php';
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0">Wallet</h1>
        </div>
    </div>

    <!-- Wallet Overview -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h6 class="mb-2">Available Balance</h6>
                    <h2 class="mb-0"><?php echo $wallet_stats_display['balance']; ?></h2>
                    <small>Ready for withdrawal</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Pending Earnings</h6>
                    <h3 class="mb-0"><?php echo $wallet_stats_display['pending_earning']; ?></h3>
                    <small class="text-muted">Orders in progress</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Earned</h6>
                    <h3 class="mb-0"><?php echo $wallet_stats_display['total_earned']; ?></h3>
                    <small class="text-muted">Lifetime earnings</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Withdrawn</h6>
                    <h3 class="mb-0"><?php echo $wallet_stats_display['total_withdrawn']; ?></h3>
                    <small class="text-muted">All time</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Withdraw Money Section 
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-money-bill-wave"></i> Withdraw Money
                    </h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <input type="hidden" name="action" value="withdraw">
                        
                        <div class="form-group">
                            <label>Amount</label>
                            <input type="number" name="amount" class="form-control" 
                                   step="0.01" min="1000" 
                                   placeholder="Enter amount" required>
                            <small class="text-muted">Minimum: ₦1,000.00</small>
                        </div>

                        <div class="form-group">
                            <label>Bank Name</label>
                            <select name="bank_name" class="form-control" required>
                                <option value="">Select Bank</option>
                                <?php foreach (WalletHelper::getNigerianBanks() as $bank): ?>
                                    <option value="<?php echo $bank; ?>" <?php echo ($bank_details['bank_name'] ?? '') === $bank ? 'selected' : ''; ?>>
                                        <?php echo $bank; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Account Number</label>
                            <input type="text" name="account_number" class="form-control" 
                                   maxlength="10" pattern="[0-9]{10}" 
                                   value="<?php echo htmlspecialchars($bank_details['account_number'] ?? ''); ?>"
                                   placeholder="0123456789" required>
                        </div>

                        <div class="form-group">
                            <label>Account Name</label>
                            <input type="text" name="account_name" class="form-control" 
                                   value="<?php echo htmlspecialchars($bank_details['account_name'] ?? ''); ?>"
                                   placeholder="Your account name" required>
                        </div>

                        <button type="submit" class="btn btn-success btn-block">
                            <i class="fas fa-paper-plane"></i> Request Withdrawal
                        </button>
                    </form>
                </div>
            </div>

            
            <div class="card mt-3">
                <div class="card-header">
                    <h5 class="mb-0">Withdrawal History</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($withdrawal_history)): ?>
                        <p class="text-muted">No withdrawal requests yet</p>
                    <?php else: ?>
                        <?php foreach ($withdrawal_history as $wd): ?>
                            <div class="mb-3 pb-3 border-bottom">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <strong><?php echo WalletHelper::formatMoney($wd['amount']); ?></strong>
                                        <br>
                                        <small class="text-muted"><?php echo htmlspecialchars($wd['bank_name']); ?></small>
                                        <br>
                                        <small class="text-muted"><?php echo date('M d, Y', strtotime($wd['created_at'])); ?></small>
                                    </div>
                                    <div>
                                        <?php
                                        $badge_class = 'secondary';
                                        switch($wd['status']) {
                                            case 'pending': $badge_class = 'warning'; break;
                                            case 'approved': $badge_class = 'info'; break;
                                            case 'paid': $badge_class = 'success'; break;
                                            case 'rejected': $badge_class = 'danger'; break;
                                        }
                                        ?>
                                        <span class="badge badge-<?php echo $badge_class; ?>">
                                            <?php echo ucfirst($wd['status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div> -->

        <!-- Transaction History -->
        <div class="col-md-12 mb-4">
            <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="vendor_earning" <?php echo $filter_type === 'vendor_earning' ? 'selected' : ''; ?>>Earnings</option>
                                    <option value="withdrawal" <?php echo $filter_type === 'withdrawal' ? 'selected' : ''; ?>>Withdrawals</option>
                                    <option value="commission" <?php echo $filter_type === 'commission' ? 'selected' : ''; ?>>Commission</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)): ?>
                        <p class="text-muted">No transactions found</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Amount</th>
                                        <th>Balance</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $txn): ?>
                                        <tr>
                                            <td><?php echo date('M d, Y H:i', strtotime($txn['created_at'])); ?></td>
                                            <td>
                                                <span class="badge badge-<?php echo $txn['category'] === 'credit' ? 'success' : 'warning'; ?>">
                                                    <?php echo WalletHelper::getTransactionTypeLabel($txn['transaction_type']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($txn['description']); ?>
                                                <?php if (!empty($txn['order_number'])): ?>
                                                    <br><small class="text-muted">Order: <?php echo htmlspecialchars($txn['order_number']); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td class="<?php echo $txn['category'] === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                                <strong>
                                                    <?php echo $txn['category'] === 'credit' ? '+' : '-'; ?>
                                                    <?php echo WalletHelper::formatMoney($txn['amount']); ?>
                                                </strong>
                                            </td>
                                            <td><?php echo WalletHelper::formatMoney($txn['balance_after']); ?></td>
                                            <td>
                                                <span class="badge badge-<?php echo WalletHelper::getStatusBadgeClass($txn['status']); ?>">
                                                    <?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 for ($i = 1; $i <= $total_pages; $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; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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