<?php
/**
 * Payment Methods Management Functions
 * Safe implementation for production use
 */

/**
 * Get all active payment methods from database
 * @param mysqli $conn Database connection
 * @return array Array of payment methods
 */
function getActivePaymentMethods($conn) {
    $methods = [];
    $query = "SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order, method_name";
    
    $result = $conn->query($query);
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $methods[] = $row;
        }
    }
    
    return $methods;
}

/**
 * Get payment method by name
 * @param mysqli $conn Database connection
 * @param string $method_name Payment method name
 * @return array|null Payment method data or null if not found
 */
function getPaymentMethodByName($conn, $method_name) {
    $stmt = $conn->prepare("SELECT * FROM payment_methods WHERE method_name = ? AND is_active = 1");
    $stmt->bind_param("s", $method_name);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

/**
 * Check if payment method requires bank account
 * @param mysqli $conn Database connection
 * @param string $method_name Payment method name
 * @return bool True if requires bank account
 */
function paymentMethodRequiresBankAccount($conn, $method_name) {
    $method = getPaymentMethodByName($conn, $method_name);
    return $method ? (bool)$method['requires_bank_account'] : false;
}

/**
 * Generate payment method options for select dropdowns
 * @param mysqli $conn Database connection
 * @param string $selected_method Currently selected method
 * @param bool $include_credit Whether to include credit option
 * @return string HTML options
 */
function generatePaymentMethodOptions($conn, $selected_method = '', $include_credit = true) {
    $methods = getActivePaymentMethods($conn);
    $options = '';
    
    foreach ($methods as $method) {
        // Skip credit if not included
        if (!$include_credit && $method['method_name'] === 'credit') {
            continue;
        }
        
        $selected = ($selected_method === $method['method_name']) ? 'selected' : '';
        $display_name = $method['display_name'] ?: ucfirst($method['method_name']);
        $options .= "<option value=\"{$method['method_name']}\" {$selected}>{$display_name}</option>";
    }
    
    return $options;
}

/**
 * Generate payment method buttons for POS
 * @param mysqli $conn Database connection
 * @return string HTML buttons
 */
function generatePaymentMethodButtons($conn) {
    $methods = getActivePaymentMethods($conn);
    $buttons = '';
    
    foreach ($methods as $method) {
        $icon_class = $method['icon_class'] ?: 'fas fa-money-bill';
        $color_class = $method['color_class'] ?: 'btn-outline-primary';
        $display_name = $method['display_name'] ?: ucfirst($method['method_name']);
        
        $data_requires_bank = $method['requires_bank_account'] ? 'data-requires-bank="1"' : '';
        
        $buttons .= "<button type=\"button\" class=\"btn {$color_class} payment-option\" data-method=\"{$method['method_name']}\" {$data_requires_bank}>";
        $buttons .= "<i class=\"{$icon_class}\"></i> {$display_name}";
        $buttons .= "</button>";
    }
    
    return $buttons;
}

/**
 * Validate payment method
 * @param mysqli $conn Database connection
 * @param string $method_name Payment method name
 * @return bool True if valid
 */
function isValidPaymentMethod($conn, $method_name) {
    $method = getPaymentMethodByName($conn, $method_name);
    return $method !== null;
}

/**
 * Get payment method display name
 * @param mysqli $conn Database connection
 * @param string $method_name Payment method name
 * @return string Display name
 */
function getPaymentMethodDisplayName($conn, $method_name) {
    $method = getPaymentMethodByName($conn, $method_name);
    return $method ? ($method['display_name'] ?: ucfirst($method['method_name'])) : ucfirst($method_name);
}

/**
 * Add new payment method (Admin function)
 * @param mysqli $conn Database connection
 * @param array $data Payment method data
 * @return bool Success status
 */
function addPaymentMethod($conn, $data) {
    $stmt = $conn->prepare("INSERT INTO payment_methods (method_name, display_name, icon_class, color_class, is_active, requires_bank_account, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssiii", 
        $data['method_name'],
        $data['display_name'],
        $data['icon_class'],
        $data['color_class'],
        $data['is_active'],
        $data['requires_bank_account'],
        $data['sort_order']
    );
    return $stmt->execute();
}

/**
 * Update payment method (Admin function)
 * @param mysqli $conn Database connection
 * @param int $id Payment method ID
 * @param array $data Payment method data
 * @return bool Success status
 */
function updatePaymentMethod($conn, $id, $data) {
    $stmt = $conn->prepare("UPDATE payment_methods SET display_name = ?, icon_class = ?, color_class = ?, is_active = ?, requires_bank_account = ?, sort_order = ? WHERE id = ?");
    $stmt->bind_param("sssiiii", 
        $data['display_name'],
        $data['icon_class'],
        $data['color_class'],
        $data['is_active'],
        $data['requires_bank_account'],
        $data['sort_order'],
        $id
    );
    return $stmt->execute();
}

/**
 * Delete payment method (Admin function - safe delete)
 * @param mysqli $conn Database connection
 * @param int $id Payment method ID
 * @return bool Success status
 */
function deletePaymentMethod($conn, $id) {
    // Check if method is in use
    $usage_check = $conn->query("SELECT COUNT(*) as count FROM sales WHERE payment_method = (SELECT method_name FROM payment_methods WHERE id = $id)");
    $usage = $usage_check->fetch_assoc();
    
    if ($usage['count'] > 0) {
        // If in use, just deactivate instead of delete
        $stmt = $conn->prepare("UPDATE payment_methods SET is_active = 0 WHERE id = ?");
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    } else {
        // If not in use, safe to delete
        $stmt = $conn->prepare("DELETE FROM payment_methods WHERE id = ?");
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    }
}
?> 