<?php
/**
 * Paystack Charge Manager Class
 * Handles Paystack top-up charge configuration
 * Example: User tops up GHS 10, admin sets charge to 0.8 pesewas (GHS 0.008), Paystack charges GHS 10.008
 */

class PaystackChargeManager {
    private $conn;
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    /**
     * Get current Paystack charge configuration
     */
    public function getChargeConfig() {
        // Check if table exists first
        $tableCheck = mysqli_query($this->conn, "SHOW TABLES LIKE 'paystack_topup_charge'");
        if (!$tableCheck || mysqli_num_rows($tableCheck) == 0) {
            // Table doesn't exist, return default configuration
            return [
                'id' => 0,
                'charge_amount' => 0.00,
                'charge_type' => 'fixed', // fixed or percentage
                '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 paystack_topup_charge 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,
            'charge_amount' => 0.00,
            'charge_type' => 'fixed',
            'is_active' => 0,
            'created_by' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
    }
    
    /**
     * Update Paystack charge configuration
     */
    public function updateChargeConfig($chargeAmount, $chargeType, $adminId) {
        // Check if table exists first
        $tableCheck = mysqli_query($this->conn, "SHOW TABLES LIKE 'paystack_topup_charge'");
        if (!$tableCheck || mysqli_num_rows($tableCheck) == 0) {
            return ['success' => false, 'message' => 'Paystack charge configuration table does not exist. Please run the setup script first.'];
        }
        
        // Validate charge amount
        if (!is_numeric($chargeAmount) || $chargeAmount < 0) {
            return ['success' => false, 'message' => 'Invalid charge amount'];
        }
        
        // Validate charge type
        if (!in_array($chargeType, ['fixed', 'percentage'])) {
            return ['success' => false, 'message' => 'Invalid charge type. Must be "fixed" or "percentage"'];
        }
        
        // Validate percentage range
        if ($chargeType === 'percentage' && $chargeAmount > 100) {
            return ['success' => false, 'message' => 'Percentage charge cannot exceed 100%'];
        }
        
        // Deactivate current configuration
        $deactivateSql = "UPDATE paystack_topup_charge SET is_active = 0 WHERE is_active = 1";
        mysqli_query($this->conn, $deactivateSql);
        
        // Insert new configuration
        $stmt = $this->conn->prepare("
            INSERT INTO paystack_topup_charge (charge_amount, charge_type, is_active, created_by, created_at, updated_at) 
            VALUES (?, ?, 1, ?, NOW(), NOW())
        ");
        
        $stmt->bind_param("dsi", $chargeAmount, $chargeType, $adminId);
        
        if ($stmt->execute()) {
            $stmt->close();
            return ['success' => true, 'message' => 'Paystack charge configuration updated successfully'];
        } else {
            $stmt->close();
            return ['success' => false, 'message' => 'Failed to update configuration: ' . mysqli_error($this->conn)];
        }
    }
    
    /**
     * Calculate total amount including charge
     * @param float $baseAmount - The amount user wants to top up
     * @return array - Contains total_amount, charge_amount, base_amount
     */
    public function calculateChargedAmount($baseAmount) {
        $config = $this->getChargeConfig();
        
        if (!$config['is_active']) {
            return [
                'base_amount' => $baseAmount,
                'charge_amount' => 0.00,
                'total_amount' => $baseAmount,
                'charge_type' => 'none'
            ];
        }
        
        $chargeAmount = floatval($config['charge_amount']);
        $chargeType = $config['charge_type'];
        $calculatedCharge = 0.00;
        
        if ($chargeType === 'fixed') {
            // Fixed charge in GHS
            $calculatedCharge = $chargeAmount;
        } elseif ($chargeType === 'percentage') {
            // Percentage charge
            $calculatedCharge = ($baseAmount * $chargeAmount) / 100;
        }
        
        $totalAmount = $baseAmount + $calculatedCharge;
        
        return [
            'base_amount' => $baseAmount,
            'charge_amount' => $calculatedCharge,
            'total_amount' => $totalAmount,
            'charge_type' => $chargeType
        ];
    }
    
    /**
     * Get charge amount for display
     */
    public function getChargeAmount() {
        $config = $this->getChargeConfig();
        return $config['is_active'] ? floatval($config['charge_amount']) : 0;
    }
    
    /**
     * Get charge type
     */
    public function getChargeType() {
        $config = $this->getChargeConfig();
        return $config['charge_type'] ?? 'fixed';
    }
    
    /**
     * Check if charge is enabled
     */
    public function isChargeEnabled() {
        $config = $this->getChargeConfig();
        return $config['is_active'] == 1;
    }
    
    /**
     * Get charge description for display
     */
    public function getChargeDescription() {
        $config = $this->getChargeConfig();
        
        if (!$config['is_active']) {
            return 'No charges applied';
        }
        
        $amount = floatval($config['charge_amount']);
        $type = $config['charge_type'];
        
        if ($type === 'fixed') {
            return 'GHS ' . number_format($amount, 2) . ' flat charge';
        } else {
            return number_format($amount, 2) . '% charge';
        }
    }
    
    /**
     * Get configuration history
     */
    public function getConfigurationHistory($limit = 10) {
        // Check if table exists first
        $tableCheck = mysqli_query($this->conn, "SHOW TABLES LIKE 'paystack_topup_charge'");
        if (!$tableCheck || mysqli_num_rows($tableCheck) == 0) {
            return [];
        }
        
        $sql = "SELECT * FROM paystack_topup_charge 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;
    }
    
    /**
     * Disable charge
     */
    public function disableCharge() {
        $sql = "UPDATE paystack_topup_charge SET is_active = 0 WHERE is_active = 1";
        if (mysqli_query($this->conn, $sql)) {
            return ['success' => true, 'message' => 'Paystack charge disabled successfully'];
        } else {
            return ['success' => false, 'message' => 'Failed to disable charge: ' . mysqli_error($this->conn)];
        }
    }
}
?>


