<?php
/**
 * Minimum Top-up Manager Class
 * Handles minimum top-up configuration and validation
 */

class MinimumTopupManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Get current minimum top-up configuration
     */
    public function getMinimumTopupConfig() {
        // Check if table exists first
        $tableCheck = mysqli_query($this->conn, "SHOW TABLES LIKE 'minimum_topup_config'");
        if (!$tableCheck || mysqli_num_rows($tableCheck) == 0) {
            // Table doesn't exist, return default configuration
            return [
                'id' => 0,
                'minimum_amount' => 10.00,
                'is_active' => 0, // Disabled by default if table doesn't exist
                'created_by' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
        }
        
        $sql = "SELECT * FROM minimum_topup_config WHERE is_active = 1 ORDER BY id DESC LIMIT 1";
        $result = mysqli_query($this->conn, $sql);
        
        if ($result && mysqli_num_rows($result) > 0) {
            return mysqli_fetch_assoc($result);
        }
        
        // Return default if no configuration found
        return [
            'id' => 0,
            'minimum_amount' => 10.00,
            'is_active' => 1,
            'created_by' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
    }
    
    /**
     * Update minimum top-up configuration
     */
    public function updateMinimumTopupConfig($minimumAmount, $adminId) {
        // Check if table exists first
        $tableCheck = mysqli_query($this->conn, "SHOW TABLES LIKE 'minimum_topup_config'");
        if (!$tableCheck || mysqli_num_rows($tableCheck) == 0) {
            return ['success' => false, 'message' => 'Minimum top-up configuration table does not exist. Please run the setup script first.'];
        }
        
        // Validate minimum amount
        if (!is_numeric($minimumAmount) || $minimumAmount < 0) {
            return ['success' => false, 'message' => 'Invalid minimum amount'];
        }
        
        // Deactivate current configuration
        $deactivateSql = "UPDATE minimum_topup_config SET is_active = 0 WHERE is_active = 1";
        mysqli_query($this->conn, $deactivateSql);
        
        // Insert new configuration
        $stmt = $this->conn->prepare("
            INSERT INTO minimum_topup_config (minimum_amount, is_active, created_by, created_at, updated_at) 
            VALUES (?, 1, ?, NOW(), NOW())
        ");
        
        $stmt->bind_param("di", $minimumAmount, $adminId);
        
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Minimum top-up configuration updated successfully'];
        } else {
            $stmt->close();
            return ['success' => false, 'message' => 'Failed to update configuration: ' . mysqli_error($this->conn)];
        }
    }
    
    /**
     * Validate top-up amount against minimum
     */
    public function validateTopupAmount($amount) {
        $config = $this->getMinimumTopupConfig();
        
        if (!$config['is_active']) {
            return ['valid' => true, 'message' => 'Minimum top-up validation is disabled'];
        }
        
        $minimumAmount = floatval($config['minimum_amount']);
        $topupAmount = floatval($amount);
        
        if ($topupAmount < $minimumAmount) {
            return [
                'valid' => false, 
                'message' => "Minimum top-up amount is GHS " . number_format($minimumAmount, 2) . ". Please enter an amount of GHS " . number_format($minimumAmount, 2) . " or more.",
                'minimum_amount' => $minimumAmount
            ];
        }
        
        return ['valid' => true, 'message' => 'Amount is valid'];
    }
    
    /**
     * Get minimum top-up amount for display
     */
    public function getMinimumAmount() {
        $config = $this->getMinimumTopupConfig();
        return $config['is_active'] ? floatval($config['minimum_amount']) : 0;
    }
    
    /**
     * Check if minimum top-up is enabled
     */
    public function isMinimumTopupEnabled() {
        $config = $this->getMinimumTopupConfig();
        return $config['is_active'] == 1;
    }
    
    /**
     * Get configuration history
     */
    public function getConfigurationHistory($limit = 10) {
        $sql = "SELECT * FROM minimum_topup_config ORDER BY created_at DESC LIMIT ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("i", $limit);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $history = [];
        while ($row = $result->fetch_assoc()) {
            $history[] = $row;
        }
        
        $stmt->close();
        return $history;
    }
}
?>
