<?php
/**
 * VENDOR DASHBOARD PAGE
 * File: vendor/index.php
 * UPDATED WITH NEW WALLET SYSTEM V4.0 - Uses WalletStats
 */

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

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

// Initialize models
$vendorModel = new Vendor();
$itemModel = new Item();
$orderModel = new Order();
$walletTransactionModel = new WalletTransaction();

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

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

if (!$vendor_data) {
    flash('error', 'Vendor profile not found.', 'danger');
    redirect('profile.php');
}

$vendor_id = $vendor_data['id'];
$db = Database::getInstance();

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



// Get vendor wallet
$vendor_wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ? AND user_type = 'vendor'", [$user_id]);
if (!$vendor_wallet) {
    $db->execute("INSERT INTO wallets (user_id, user_type) VALUES (?, 'vendor')", [$user_id]);
    $vendor_wallet = $db->fetch("SELECT * FROM wallets WHERE user_id = ? AND user_type = 'vendor'", [$user_id]);
}

// Get user bank details
$user_bank_details = $db->fetch("SELECT bank_name, account_name, account_number FROM users WHERE id = ?", [$user_id]);

// Get pending withdrawals
$pending_withdrawals = $db->fetchAll("
    SELECT * FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
    ORDER BY created_at DESC
    LIMIT 5
", [$user_id]);

$pending_withdrawal_total = $db->fetch("
    SELECT COALESCE(SUM(amount), 0) as total
    FROM withdrawal_requests
    WHERE user_id = ? AND status = 'pending'
", [$user_id]);


// Get order statistics
$total_orders_sql = "SELECT COUNT(*) as count FROM orders WHERE vendor_id = ?";
$total_orders_result = $db->fetch($total_orders_sql, [$vendor_id]);
$total_orders = $total_orders_result['count'] ?? 0;

$pending_orders_sql = "SELECT COUNT(*) as count FROM orders WHERE vendor_id = ? AND status = 'pending'";
$pending_orders_result = $db->fetch($pending_orders_sql, [$vendor_id]);
$pending_orders = $pending_orders_result['count'] ?? 0;

$ongoing_orders_sql = "SELECT COUNT(*) as count FROM orders WHERE vendor_id = ? AND status = 'ongoing'";
$ongoing_orders_result = $db->fetch($ongoing_orders_sql, [$vendor_id]);
$ongoing_orders = $ongoing_orders_result['count'] ?? 0;

$completed_orders_sql = "SELECT COUNT(*) as count FROM orders WHERE vendor_id = ? AND status = 'completed'";
$completed_orders_result = $db->fetch($completed_orders_sql, [$vendor_id]);
$completed_orders = $completed_orders_result['count'] ?? 0;

// Get item statistics
$total_items_sql = "SELECT COUNT(*) as count FROM items WHERE vendor_id = ?";
$total_items_result = $db->fetch($total_items_sql, [$vendor_id]);
$total_items = $total_items_result['count'] ?? 0;

$active_items_sql = "SELECT COUNT(*) as count FROM items WHERE vendor_id = ? AND approval_status = 'approved'";
$active_items_result = $db->fetch($active_items_sql, [$vendor_id]);
$active_items = $active_items_result['count'] ?? 0;

$pending_items_sql = "SELECT COUNT(*) as count FROM items WHERE vendor_id = ? AND approval_status = 'pending'";
$pending_items_result = $db->fetch($pending_items_sql, [$vendor_id]);
$pending_items = $pending_items_result['count'] ?? 0;

// Get recent orders
$recent_orders_sql = "SELECT o.*, 
                      i.title as item_title,
                      i.main_image as item_image,
                      CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                      cu.email as customer_email
                      FROM orders o
                      LEFT JOIN items i ON o.item_id = i.id
                      LEFT JOIN customers c ON o.customer_id = c.id
                      LEFT JOIN users cu ON c.user_id = cu.id
                      WHERE o.vendor_id = ?
                      ORDER BY o.created_at DESC
                      LIMIT 10";
$recent_orders = $db->fetchAll($recent_orders_sql, [$vendor_id]);

// Get recent transactions using WalletStats
$recent_transactions = $walletStats->getVendorTransactions($user_id, 5);

// Get average rating
$rating_sql = "SELECT AVG(rating) as avg_rating, COUNT(*) as total_reviews
               FROM reviews 
               WHERE vendor_id = ? AND status = 'active'";
$rating_data = $db->fetch($rating_sql, [$vendor_id]);
$avg_rating = $rating_data['avg_rating'] ?? 0;
$total_reviews = $rating_data['total_reviews'] ?? 0;

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

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-0">Dashboard</h1>
            <p class="text-muted">Welcome back, <?php echo htmlspecialchars($vendor_data['business_name']); ?>!</p>
        </div>
    </div>

    <!-- Vendor Dashboard Cards - Using WalletStats -->
    <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>Withdrawable</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.3;">💵</div>
                    </div>
                    
                    <?php if (!empty($pending_withdrawals)): ?>
                        <!-- Show pending info -->
                        <div class="alert alert-warning text-dark mt-3 mb-0 p-2">
                            <small>
                                <i class="fas fa-clock"></i> 
                                <strong>₦<?php echo number_format($pending_withdrawal_total['total'], 2); ?></strong> pending
                            </small>
                        </div>
                    <?php else: ?>
                        <!-- Show withdraw button -->
                        <button class="btn btn-light btn-sm mt-2 w-100" 
                                onclick="openVendorWithdrawModal()"
                                <?php if ($wallet_cards['available_balance'] < 5000): ?>disabled<?php endif; ?>>
                            <i class="fas fa-money-bill-wave"></i> Withdraw Funds
                        </button>
                        <?php if ($wallet_cards['available_balance'] < 5000): ?>
                            <small class="d-block mt-1" style="font-size: 0.7rem;">Minimum: ₦5000</small>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Card 2: Pending Earnings -->
        <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">Pending Earnings</h6>
                            <h2 class="mb-0">₦<?php echo number_format($wallet_cards['pending_earning'], 2); ?></h2>
                            <small>From ongoing orders</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.3;">⏳</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 3: Total Earned -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-2">Total Earned</h6>
                            <h3 class="mb-0">₦<?php echo number_format($wallet_cards['total_earned'], 2); ?></h3>
                            <small class="text-muted">Lifetime earnings</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.2;">📈</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card 4: Total Withdrawn -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="text-muted mb-2">Total Withdrawn</h6>
                            <h3 class="mb-0">₦<?php echo number_format($wallet_cards['total_withdrawn'], 2); ?></h3>
                            <small class="text-muted">All time payouts</small>
                        </div>
                        <div style="font-size: 36px; opacity: 0.2;">🏦</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Orders & Items Statistics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Total Items</h6>
                    <h3><?php echo $total_items; ?></h3>
                    <small class="text-muted">
                        <span class="text-success"><?php echo $active_items; ?> active</span> | 
                        <span class="text-warning"><?php echo $pending_items; ?> pending</span>
                    </small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Total Orders</h6>
                    <h3><?php echo $total_orders; ?></h3>
                    <small class="text-muted">All time</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Ongoing Orders</h6>
                    <h3><?php echo $ongoing_orders; ?></h3>
                    <small class="text-muted">Active rentals</small>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted">Average Rating</h6>
                    <h3>
                        <?php echo number_format($avg_rating, 1); ?> 
                        <i class="fas fa-star text-warning"></i>
                    </h3>
                    <small class="text-muted"><?php echo $total_reviews; ?> reviews</small>
                </div>
            </div>
        </div>
    </div>


    <?php if (!empty($pending_withdrawals)): ?>
        <!-- Pending Withdrawals Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-warning shadow-sm">
                    <div class="card-header" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0 text-white">
                                <i class="fas fa-clock"></i> Pending Withdrawal Requests
                            </h5>
                            <span class="badge bg-white text-danger">
                                <?php echo count($pending_withdrawals); ?> Pending
                            </span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info d-flex align-items-center mb-4">
                            <i class="fas fa-info-circle fa-2x me-3"></i>
                            <div>
                                <strong>Total Pending:</strong> 
                                ₦<?php echo number_format($pending_withdrawal_total['total'], 2); ?><br>
                                <small>Your withdrawal request is being reviewed. You'll be notified once processed.</small>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Date Requested</th>
                                        <th>Amount</th>
                                        <th>Bank Details</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending_withdrawals as $wd): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo date('M d, Y', strtotime($wd['created_at'])); ?></strong><br>
                                                <small class="text-muted"><?php echo date('h:i A', strtotime($wd['created_at'])); ?></small>
                                            </td>
                                            <td>
                                                <h5 class="mb-0 text-primary fw-bold">
                                                    ₦<?php echo number_format($wd['amount'], 2); ?>
                                                </h5>
                                            </td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($wd['bank_name']); ?></strong><br>
                                                <small class="text-muted">
                                                    <?php echo htmlspecialchars($wd['account_number']); ?> - 
                                                    <?php echo htmlspecialchars($wd['account_name']); ?>
                                                </small>
                                            </td>
                                            <td>
                                                <span class="badge bg-warning text-dark fs-6">
                                                    <i class="fas fa-clock"></i> Awaiting Approval
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="text-center mt-3">
                            <a href="withdrawals.php" class="btn btn-primary">
                                <i class="fas fa-list"></i> View All Withdrawal History
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>



    <div class="row">
        <!-- Recent Orders -->
        <div class="col-md-8 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Orders</h5>
                    <a href="orders/" class="btn btn-sm btn-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($recent_orders)): ?>
                        <p class="text-muted">No orders yet</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Order # & Item</th>
                                        <th>Customer</th>
                                        <th>Amount</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_orders as $order): ?>
                                        <tr>
                                            <td>
                                                <a href="orders/view.php?id=<?php echo $order['id']; ?>">
                                                    <?php echo htmlspecialchars($order['order_number']); ?>
                                                </a>
                                                <br>
                                                    <img src="<?= upload('items/' . $order['item_image']) ?>" 
                                                                    style="width: 70px; object-fit: cover; border-radius: 5px;" 
                                                                    class="me-2"><br>
                                                    <span><?= htmlspecialchars($order['item_title']) ?></span>
                                            </td>
                                            <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                                            <td>
                                                <b><?php echo format_money($order['total_amount']); ?></b><br><br>
                                                <small>
                                                    R: <?php echo format_money($order['subtotal']); ?><br>
                                                    S: <?php echo format_money($order['security_deposit']); ?>
                                                </small>
                                            </td>
                                            <td>
                                                <b><?php echo date('M d, Y', strtotime($order['created_at'])); ?></b><br><br>
                                                <small>
                                                    <b><span class="text-muted">(<?= $order['rental_days'] ?> days)</span></b><br>
                                                    <?= date('M d', strtotime($order['start_date'])) ?> - 
                                                    <?= date('M d', strtotime($order['end_date'])) ?><br>
                                                    
                                                </small>
                                            </td>
                                            <td>
                                                <?php
                                                $badge_class = 'secondary';
                                                switch($order['status']) {
                                                    case 'pending': $badge_class = 'warning'; break;
                                                    case 'confirmed': $badge_class = 'info'; break;
                                                    case 'ongoing': $badge_class = 'primary'; break;
                                                    case 'completed': $badge_class = 'success'; break;
                                                    case 'cancelled': $badge_class = 'danger'; break;
                                                }
                                                ?>
                                                <span class="badge bg-<?php echo $badge_class; ?>">
                                                    <?php echo ucfirst($order['status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Transactions</h5>
                    <a href="wallet.php" class="btn btn-sm btn-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($recent_transactions)): ?>
                        <p class="text-muted">No transactions yet</p>
                    <?php else: ?>
                        <?php foreach ($recent_transactions as $txn): ?>
                            <div class="mb-3 pb-3 border-bottom">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <strong><?php echo $walletStats->getTransactionTypeLabel($txn['transaction_type']); ?></strong>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo date('M d, Y H:i', strtotime($txn['created_at'])); ?>
                                        </small>
                                    </div>
                                    <div class="text-right">
                                        <span class="<?php echo $txn['category'] === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                            <strong>
                                                <?php echo $txn['category'] === 'credit' ? '+' : '-'; ?>
                                                ₦<?php echo number_format($txn['amount'], 2); ?>
                                            </strong>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Withdrawal Modal -->
<div class="modal fade" id="vendorWithdrawModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-money-bill-wave me-2"></i> Withdraw Funds
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- Available Balance -->
                <div class="alert alert-info mb-4">
                    <div class="d-flex justify-content-between align-items-center">
                        <span><strong>Available Balance:</strong></span>
                        <span class="fs-5 fw-bold">₦<?php echo number_format($wallet_cards['available_balance'], 2); ?></span>
                    </div>
                </div>

                <form id="vendorWithdrawForm">
                    <!-- Amount -->
                    <div class="mb-3">
                        <label class="form-label fw-bold">Withdrawal Amount <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text">₦</span>
                            <input type="number" 
                                   class="form-control form-control-lg" 
                                   id="vendorWithdrawAmount" 
                                   name="amount" 
                                   placeholder="Enter amount"
                                   min="5000"
                                   max="<?php echo $wallet_cards['available_balance']; ?>"
                                   step="0.01"
                                   required>
                        </div>
                        <small class="text-muted">Minimum: ₦5000 | Maximum: ₦<?php echo number_format($wallet_cards['available_balance'], 2); ?></small>
                        <div class="invalid-feedback" id="vendorAmountError"></div>
                    </div>

                    <!-- Bank Details -->
                    <div class="mb-3">
                        <label class="form-label fw-bold">Bank Name</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_bank_details['bank_name'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Account Name</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_bank_details['account_name'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Account Number</label>
                        <input type="text" 
                               class="form-control" 
                               value="<?php echo htmlspecialchars($user_bank_details['account_number'] ?? 'Not Set'); ?>" 
                               readonly>
                    </div>

                    <?php if (empty($user_bank_details['bank_name']) || empty($user_bank_details['account_number'])): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 
                            Please <a href="profile.php" class="alert-link">update your bank details</a> before withdrawing.
                        </div>
                    <?php endif; ?>

                    <input type="hidden" name="wallet_id" value="<?php echo $vendor_wallet['id']; ?>">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" 
                        class="btn btn-success" 
                        id="vendorSubmitWithdrawBtn"
                        onclick="submitVendorWithdrawal()"
                        <?php if (empty($user_bank_details['bank_name']) || empty($user_bank_details['account_number'])): ?>
                            disabled
                        <?php endif; ?>>
                    <i class="fas fa-paper-plane"></i> Submit Withdrawal Request
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Withdrawal JavaScript -->
<script>
const VENDOR_AVAILABLE_BALANCE = <?php echo $wallet_cards['available_balance']; ?>;

function openVendorWithdrawModal() {
    if (VENDOR_AVAILABLE_BALANCE < 5000) {
        alert('Insufficient balance. Minimum withdrawal is ₦5,000.00');
        return;
    }
    const modal = new bootstrap.Modal(document.getElementById('vendorWithdrawModal'));
    modal.show();
}

function validateVendorAmount() {
    const amountInput = document.getElementById('vendorWithdrawAmount');
    const amount = parseFloat(amountInput.value);
    const errorDiv = document.getElementById('vendorAmountError');
    
    amountInput.classList.remove('is-invalid');
    errorDiv.textContent = '';
    
    if (!amount || amount <= 0) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Please enter a valid amount';
        return false;
    }
    
    if (amount < 5000) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Minimum withdrawal is ₦5,000.00';
        return false;
    }
    
    if (amount > VENDOR_AVAILABLE_BALANCE) {
        amountInput.classList.add('is-invalid');
        errorDiv.textContent = 'Amount exceeds available balance of ₦' + VENDOR_AVAILABLE_BALANCE.toLocaleString('en-NG', {minimumFractionDigits: 2});
        return false;
    }
    
    return true;
}

function submitVendorWithdrawal() {
    if (!validateVendorAmount()) {
        return;
    }
    
    const amount = parseFloat(document.getElementById('vendorWithdrawAmount').value);
    
    if (!confirm(`Confirm withdrawal of ₦${amount.toLocaleString('en-NG', {minimumFractionDigits: 2})}?\n\nThis will be sent to your registered bank account.`)) {
        return;
    }
    
    const btn = document.getElementById('vendorSubmitWithdrawBtn');
    const originalHTML = btn.innerHTML;
    
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    const formData = new FormData(document.getElementById('vendorWithdrawForm'));
    
    fetch('../api/vendor-withdraw.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✓ ' + data.message);
            bootstrap.Modal.getInstance(document.getElementById('vendorWithdrawModal')).hide();
            location.reload();
        } else {
            alert('✗ Error: ' + data.error);
            btn.disabled = false;
            btn.innerHTML = originalHTML;
        }
    })
    .catch(error => {
        alert('✗ Failed to process withdrawal. Please try again.');
        btn.disabled = false;
        btn.innerHTML = originalHTML;
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const amountInput = document.getElementById('vendorWithdrawAmount');
    if (amountInput) {
        amountInput.addEventListener('input', validateVendorAmount);
    }
});
</script>

<style>
#vendorWithdrawModal .modal-content {
    border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}

#vendorWithdrawModal .form-control:read-only {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

#vendorWithdrawModal .form-control-lg {
    font-size: 1.5rem;
    font-weight: bold;
}

#vendorWithdrawModal .alert-info {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
}
</style>


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