<?php
include 'include/header.php';

// Verify vendor session
if (!isset($_SESSION['vendor_id']) || empty($_SESSION['vendor_id'])) {
    die("Error: Vendor session not valid. Please log in again.");
}
$vendor_id = $_SESSION['vendor_id'];

// Initialize default values
$default_wallet = [
    'balance' => 0.00,
    'pending_balance' => 0.00,
    'wallet_id' => 'VENDE1C61065' // Static wallet ID
];

$default_vendor = [
    'business_name' => 'Not available',
    'vendor_id' => $vendor_id,
    'business_address' => 'Address not specified',
    'email' => 'No email provided'
];

// Get wallet balance
$wallet = $default_wallet;
$wallet_query = "SELECT balance, pending_balance FROM vendor_wallets WHERE vendor_id = ?";
$stmt = $conn->prepare($wallet_query);
$stmt->bind_param("s", $vendor_id);

if ($stmt->execute()) {
    $wallet_result = $stmt->get_result();
    if ($wallet_result->num_rows > 0) {
        $wallet_data = $wallet_result->fetch_assoc();
        $wallet['balance'] = $wallet_data['balance'];
        $wallet['pending_balance'] = $wallet_data['pending_balance'];
    }
} else {
    error_log("Wallet query failed: " . $stmt->error);
}

// Get vendor info
$vendor = $default_vendor;
$vendor_query = "SELECT business_name, vendor_id, address, email FROM vendors WHERE id = ?";
$stmt = $conn->prepare($vendor_query);
$stmt->bind_param("s", $vendor_id);

if ($stmt->execute()) {
    $vendor_result = $stmt->get_result();
    if ($vendor_result->num_rows > 0) {
        $vendor = $vendor_result->fetch_assoc();
    }
} else {
    error_log("Vendor query failed: " . $stmt->error);
}

// Get recent transactions
$transactions = [];
$transactions_query = "SELECT * FROM vendor_wallet_transactions 
                      WHERE vendor_id = ? 
                      ORDER BY created_at DESC 
                      LIMIT 5";
$stmt = $conn->prepare($transactions_query);
$stmt->bind_param("s", $vendor_id);

if ($stmt->execute()) {
    $transactions_result = $stmt->get_result();
    while ($row = $transactions_result->fetch_assoc()) {
        $transactions[] = $row;
    }
} else {
    error_log("Transactions query failed: " . $stmt->error);
}

// Get bank accounts
$has_bank_account = false;
$bank_accounts = [];
$bank_query = "SELECT * FROM vendor_bank_accounts 
              WHERE vendor_id = ? 
              AND is_verified = 1";
$stmt = $conn->prepare($bank_query);
$stmt->bind_param("s", $vendor_id);

if ($stmt->execute()) {
    $bank_result = $stmt->get_result();
    $has_bank_account = $bank_result->num_rows > 0;
    while ($row = $bank_result->fetch_assoc()) {
        $bank_accounts[] = $row;
    }
} else {
    error_log("Bank accounts query failed: " . $stmt->error);
}
?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Balance Card -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700 lg:col-span-1">
        <div class="flex justify-between items-start mb-4">
            <div>
                <h3 class="text-lg font-semibold dark:text-white">Account Balance</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">Current available funds</p>
            </div>
            <div class="w-12 h-12 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center">
                <i class="fas fa-wallet text-primary-500 dark:text-primary-600 text-xl"></i>
            </div>
        </div>
        
        <div class="space-y-4">
            <div class="balance-card bg-green-50 dark:bg-gray-700 p-4 rounded-lg">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Approved Money</p>
                        <p class="text-2xl font-bold text-green-600 dark:text-green-400">$<?= number_format($wallet['balance'], 2) ?></p>
                    </div>
                    <i class="fas fa-check-circle text-green-500 dark:text-green-400 text-xl"></i>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">Available for withdrawal</p>
            </div>
            
            <div class="balance-card bg-yellow-50 dark:bg-gray-700 p-4 rounded-lg">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Unapproved Money</p>
                        <p class="text-2xl font-bold text-yellow-600 dark:text-yellow-400">$<?= number_format($wallet['pending_balance'], 2) ?></p>
                    </div>
                    <i class="fas fa-clock text-yellow-500 dark:text-yellow-400 text-xl"></i>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">Pending clearance (2-3 days)</p>
            </div>
        </div>
        
        <div class="flex flex-col space-y-3 mt-6">
            <button onclick="<?= $has_bank_account ? 'openWithdrawModal()' : 'alert(\'Please add a verified bank account first\')' ?>" 
                    class="w-full bg-primary-500 dark:bg-primary-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
                <i class="fas fa-money-bill-wave mr-1"></i> Withdraw Funds
            </button>
            <button onclick="location.href='transactions.php'" 
                    class="w-full bg-white dark:bg-gray-700 text-primary-500 dark:text-primary-400 border border-primary-500 dark:border-primary-400 px-4 py-2 rounded-lg text-sm font-medium">
                <i class="fas fa-history mr-1"></i> Transaction History
            </button>
        </div>
    </div>

    <!-- Vendor Info -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700 lg:col-span-2">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold dark:text-white">Vendor Information</h3>
            <button onclick="location.href='bank-account.php'" class="text-primary-500 dark:text-primary-400 text-sm font-medium">
                <i class="fas fa-bank mr-1"></i> Manage Bank Accounts
            </button>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div class="bg-primary-50 dark:bg-gray-700 p-4 rounded-lg">
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Today's Earnings</p>
                <p class="text-2xl font-bold text-primary-600 dark:text-primary-400">$<?= number_format(getTodaysEarnings($conn, $vendor_id), 2) ?></p>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1"><?= getEarningsChange($conn, $vendor_id) ?> from yesterday</p>
            </div>
            <div class="bg-primary-50 dark:bg-gray-700 p-4 rounded-lg">
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Total Transactions</p>
                <p class="text-2xl font-bold text-primary-600 dark:text-primary-400"><?= getTotalTransactions($conn, $vendor_id) ?></p>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1"><?= getWeeklyTransactionsChange($conn, $vendor_id) ?> this week</p>
            </div>
        </div>
        
        <div class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Vendor Name</label>
                <p class="text-gray-900 dark:text-white"><?= htmlspecialchars($vendor['business_name']) ?></p>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Vendor Wallet ID</label>
                <p class="text-gray-900 dark:text-white">VENDE1C61065</p>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Location</label>
                <p class="text-gray-900 dark:text-white"><?= htmlspecialchars($vendor['address']) ?></p>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Contact Email</label>
                <p class="text-gray-900 dark:text-white"><?= htmlspecialchars($vendor['email']) ?></p>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700 lg:col-span-3" style="margin-bottom: 50px;">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold dark:text-white">Recent Transactions</h3>
            <button onclick="location.href='transactions.php'" class="text-primary-500 dark:text-primary-400 text-sm font-medium">View All</button>
        </div>
        <div class="space-y-3">
            <?php if (!empty($transactions)): ?>
                <?php foreach ($transactions as $transaction): ?>
                <div class="flex items-center p-4 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition">
                    <div class="w-10 h-10 bg-primary-100 dark:bg-primary-200 rounded-full flex items-center justify-center mr-4">
                        <i class="fas <?= getTransactionIcon($transaction['reference']) ?> text-primary-500 dark:text-primary-600"></i>
                    </div>
                    <div class="flex-1">
                        <p class="font-medium dark:text-white"><?= getTransactionDescription($transaction) ?></p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            <?= date('M j, Y g:i A', strtotime($transaction['created_at'])) ?> • 
                            Transaction ID: <?= $transaction['reference'] ?>
                        </p>
                    </div>
                    <div class="text-right">
                        <p class="font-medium <?= $transaction['transaction_type'] === 'credit' ? 'text-green-500' : 'text-red-500' ?>">
                            <?= $transaction['transaction_type'] === 'credit' ? '+' : '-' ?>$<?= number_format($transaction['amount'], 2) ?>
                        </p>
                        <p class="text-xs <?= getStatusColorClass($transaction['status']) ?>">
                            <?= ucfirst($transaction['status']) ?>
                        </p>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="text-center py-4 text-gray-500 dark:text-gray-400">
                    No recent transactions found
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Withdraw Modal -->
<div id="withdrawModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold dark:text-white">Withdraw Funds</h3>
            <button onclick="closeWithdrawModal()" class="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form id="withdrawForm" onsubmit="submitWithdrawal(event)">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Bank Account</label>
                <select name="bank_account" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white" required>
                    <?php if (!empty($bank_accounts)): ?>
                        <?php foreach ($bank_accounts as $bank): ?>
                        <option value="<?= $bank['id'] ?>">
                            <?= htmlspecialchars($bank['bank_name']) ?> - <?= htmlspecialchars($bank['account_number']) ?> (<?= htmlspecialchars($bank['account_name']) ?>)
                        </option>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <option disabled selected>No verified bank accounts</option>
                    <?php endif; ?>
                </select>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Amount</label>
                <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">$</span>
                    <input type="number" name="amount" min="10" max="<?= $wallet['balance'] ?>" step="0.01" 
                           class="pl-8 w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white" 
                           placeholder="0.00" required>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Available: $<?= number_format($wallet['balance'], 2) ?></p>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Withdrawal PIN</label>
                <input type="password" name="withdrawal_pin" maxlength="6" 
                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white" 
                       placeholder="Enter 6-digit PIN" required>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    <a href="#" onclick="openSetPinModal()" class="text-primary-500 hover:text-primary-600">Forgot PIN?</a>
                </p>
            </div>
            
            <div class="flex justify-end space-x-3">
                <button type="button" onclick="closeWithdrawModal()" class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
                    Cancel
                </button>
                <button type="submit" class="px-4 py-2 bg-primary-500 dark:bg-primary-600 border border-transparent rounded-md text-sm font-medium text-white hover:bg-primary-600 dark:hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                    Submit Withdrawal
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Set PIN Modal -->
<div id="setPinModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold dark:text-white">Set Withdrawal PIN</h3>
            <button onclick="closeSetPinModal()" class="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form id="setPinForm" onsubmit="setWithdrawalPin(event)">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">New 6-digit PIN</label>
                <input type="password" name="new_pin" maxlength="6" pattern="\d{6}" 
                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white" 
                       placeholder="123456" required>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Confirm PIN</label>
                <input type="password" name="confirm_pin" maxlength="6" pattern="\d{6}" 
                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-white" 
                       placeholder="123456" required>
            </div>
            
            <div class="flex justify-end space-x-3">
                <button type="button" onclick="closeSetPinModal()" class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
                    Cancel
                </button>
                <button type="submit" class="px-4 py-2 bg-primary-500 dark:bg-primary-600 border border-transparent rounded-md text-sm font-medium text-white hover:bg-primary-600 dark:hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                    Set PIN
                </button>
            </div>
        </form>
    </div>
</div>

<?php include 'include/footer.php'; ?>

<?php
// Helper functions
function getTodaysEarnings($conn, $vendor_id) {
    $query = "SELECT SUM(amount) as total FROM vendor_wallet_transactions 
              WHERE vendor_id = ? 
              AND transaction_type = 'credit' 
              AND DATE(created_at) = CURDATE()";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $vendor_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    return $row['total'] ?? 0;
}

function getEarningsChange($conn, $vendor_id) {
    // Yesterday's earnings
    $yesterday_query = "SELECT SUM(amount) as total FROM vendor_wallet_transactions 
                       WHERE vendor_id = ? 
                       AND transaction_type = 'credit' 
                       AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
    $stmt = $conn->prepare($yesterday_query);
    $stmt->bind_param("s", $vendor_id);
    $stmt->execute();
    $yesterday_result = $stmt->get_result();
    $yesterday = $yesterday_result->fetch_assoc();
    $yesterday_total = $yesterday['total'] ?? 0;
    
    // Today's earnings
    $today_total = getTodaysEarnings($conn, $vendor_id);
    
    if ($yesterday_total == 0) {
        return "+100% from yesterday";
    }
    
    $change = (($today_total - $yesterday_total) / $yesterday_total) * 100;
    $sign = $change >= 0 ? "+" : "-";
    return $sign . abs(round($change)) . "% from yesterday";
}

function getTotalTransactions($conn, $vendor_id) {
    $query = "SELECT COUNT(*) as total FROM vendor_wallet_transactions WHERE vendor_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $vendor_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    return $row['total'] ?? 0;
}

function getWeeklyTransactionsChange($conn, $vendor_id) {
    // Last week's transactions
    $last_week_query = "SELECT COUNT(*) as total FROM vendor_wallet_transactions 
                       WHERE vendor_id = ? 
                       AND created_at BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 WEEK) AND DATE_SUB(CURDATE(), INTERVAL 1 WEEK)";
    $stmt = $conn->prepare($last_week_query);
    $stmt->bind_param("s", $vendor_id);
    $stmt->execute();
    $last_week_result = $stmt->get_result();
    $last_week = $last_week_result->fetch_assoc();
    $last_week_total = $last_week['total'] ?? 0;
    
    // This week's transactions
    $this_week_query = "SELECT COUNT(*) as total FROM vendor_wallet_transactions 
                       WHERE vendor_id = ? 
                       AND created_at >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)";
    $stmt = $conn->prepare($this_week_query);
    $stmt->bind_param("s", $vendor_id);
    $stmt->execute();
    $this_week_result = $stmt->get_result();
    $this_week = $this_week_result->fetch_assoc();
    $this_week_total = $this_week['total'] ?? 0;
    
    if ($last_week_total == 0) {
        return "+100% this week";
    }
    
    $change = (($this_week_total - $last_week_total) / $last_week_total) * 100;
    $sign = $change >= 0 ? "+" : "-";
    return $sign . abs(round($change)) . "% this week";
}

function getTransactionIcon($reference) {
    // Customize based on your transaction types
    return 'fa-money-bill-wave';
}

function getTransactionDescription($transaction) {
    if ($transaction['transaction_type'] === 'debit') {
        return "Withdrawal Request";
    }
    return "Sale Transaction";
}

function getStatusColorClass($status) {
    switch ($status) {
        case 'completed': return 'text-green-500 dark:text-green-400';
        case 'pending': return 'text-yellow-500 dark:text-yellow-400';
        case 'failed': return 'text-red-500 dark:text-red-400';
        default: return 'text-gray-500 dark:text-gray-400';
    }
}