<?php
/**
 * Zashof Payment Gateway Integration Class
 * 
 * This class handles integration with the Zashof payment gateway
 * for accepting payments from students via bKash Personal
 */

require_once dirname(__DIR__) . '/config/database.php';

class ZashofPayment {
    private $api_key;
    private $base_url;
    private $create_charge_url;
    private $verify_payment_url;
    private $enabled;
    
    public function __construct() {
        $this->loadConfig();
    }
    
    /**
     * Load configuration from database
     */
    private function loadConfig() {
        global $pdo;
        
        try {
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'zashof_%'");
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            
            $this->enabled = isset($settings['zashof_enabled']) && $settings['zashof_enabled'] == '1';
            $this->api_key = $settings['zashof_api_key'] ?? '';
            $this->base_url = $settings['zashof_base_url'] ?? '';
            $this->create_charge_url = $settings['zashof_create_charge_url'] ?? '';
            $this->verify_payment_url = $settings['zashof_verify_payment_url'] ?? '';
        } catch (Exception $e) {
            $this->enabled = false;
            $this->api_key = '';
            $this->base_url = '';
            $this->create_charge_url = '';
            $this->verify_payment_url = '';
        }
    }
    
    /**
     * Check if the payment gateway is enabled and properly configured
     */
    public function isEnabled() {
        return $this->enabled && !empty($this->api_key) && !empty($this->base_url);
    }
    
    /**
     * Get configuration status
     */
    public function getConfigStatus() {
        return [
            'enabled' => $this->enabled,
            'api_key_set' => !empty($this->api_key),
            'base_url' => $this->base_url,
            'create_charge_url' => $this->create_charge_url,
            'verify_payment_url' => $this->verify_payment_url
        ];
    }
    
    /**
     * Validate API key format
     */
    private function validateApiKey($api_key) {
        // Zashof API keys are typically long hexadecimal strings
        return !empty($api_key) && strlen($api_key) > 20;
    }
    
    /**
     * Create a payment charge
     */
    public function createCharge($amount, $student_info, $redirect_url, $cancel_url) {
        if (!$this->isEnabled()) {
            throw new Exception("Zashof payment gateway is not enabled or properly configured");
        }
        
        // Validate API key before making request
        if (!$this->validateApiKey($this->api_key)) {
            throw new Exception("Invalid API key format. Please check your Zashof API key in the admin settings.");
        }
        
        $data = [
            'amount' => $amount,
            'currency' => 'BDT',
            'redirect_url' => $redirect_url,
            'cancel_url' => $cancel_url,
            'client_name' => $student_info['name'],
            'client_email' => $student_info['email'] ?? '',
            'client_mobile' => $student_info['phone'] ?? '',
            'student_id' => $student_info['student_id'],
            'description' => 'School Fee Payment',
            'metadata' => [
                'student_id' => $student_info['student_id'],
                'student_name' => $student_info['name'],
                'payment_for' => 'school_fees'
            ]
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->create_charge_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->api_key,
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Bidda School Management System/1.0');
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        // Debug information
        error_log("Zashof API Request Debug:");
        error_log("URL: " . $this->create_charge_url);
        error_log("API Key: " . (strlen($this->api_key) > 20 ? substr($this->api_key, 0, 10) . '...' . substr($this->api_key, -10) : $this->api_key));
        error_log("HTTP Code: " . $httpCode);
        error_log("cURL Error: " . $error);
        error_log("Response: " . $response);
        
        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }
        
        // Handle HTTP errors
        if ($httpCode === 401) {
            throw new Exception("Unauthorized request. Invalid API key. Please check your Zashof API key in the admin settings.");
        }
        
        if ($httpCode === 400) {
            $errorResponse = json_decode($response, true);
            if ($errorResponse && isset($errorResponse['message'])) {
                throw new Exception("API Error: " . $errorResponse['message']);
            }
            throw new Exception("Bad Request (HTTP 400). Please check your API configuration.");
        }
        
        if ($httpCode !== 200 && $httpCode !== 201) {
            throw new Exception("API Error: HTTP " . $httpCode . " - " . $response);
        }
        
        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Invalid JSON response: " . $response);
        }
        
        return $result;
    }
    
    /**
     * Verify a payment
     */
    public function verifyPayment($transaction_id) {
        if (!$this->isEnabled()) {
            throw new Exception("Zashof payment gateway is not enabled or properly configured");
        }
        
        // Validate API key before making request
        if (!$this->validateApiKey($this->api_key)) {
            throw new Exception("Invalid API key format. Please check your Zashof API key in the admin settings.");
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->verify_payment_url . '/' . $transaction_id);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->api_key,
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Bidda School Management System/1.0');
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        // Debug information
        error_log("Zashof Verify API Request Debug:");
        error_log("URL: " . $this->verify_payment_url . '/' . $transaction_id);
        error_log("API Key: " . (strlen($this->api_key) > 20 ? substr($this->api_key, 0, 10) . '...' . substr($this->api_key, -10) : $this->api_key));
        error_log("HTTP Code: " . $httpCode);
        error_log("cURL Error: " . $error);
        error_log("Response: " . $response);
        
        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }
        
        // Handle HTTP errors
        if ($httpCode === 401) {
            throw new Exception("Unauthorized request. Invalid API key. Please check your Zashof API key in the admin settings.");
        }
        
        if ($httpCode === 400) {
            $errorResponse = json_decode($response, true);
            if ($errorResponse && isset($errorResponse['message'])) {
                throw new Exception("API Error: " . $errorResponse['message']);
            }
            throw new Exception("Bad Request (HTTP 400). Please check your API configuration.");
        }
        
        if ($httpCode !== 200) {
            throw new Exception("API Error: HTTP " . $httpCode . " - " . $response);
        }
        
        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Invalid JSON response: " . $response);
        }
        
        return $result;
    }
}

/**
 * Get Zashof configuration
 */
function get_zashof_config() {
    global $pdo;
    
    try {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'zashof_%'");
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Check if we're running from command line (no HTTP_HOST)
        $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        
        return [
            'enabled' => isset($settings['zashof_enabled']) && $settings['zashof_enabled'] == '1',
            'api_key' => $settings['zashof_api_key'] ?? '',
            'base_url' => $settings['zashof_base_url'] ?? '',
            'create_charge_url' => $settings['zashof_create_charge_url'] ?? '',
            'verify_payment_url' => $settings['zashof_verify_payment_url'] ?? '',
            'redirect_url' => 'http://' . $host . '/fees/zashof_success.php',
            'cancel_url' => 'http://' . $host . '/fees/my_fees.php'
        ];
    } catch (Exception $e) {
        return [
            'enabled' => false,
            'api_key' => '',
            'base_url' => '',
            'create_charge_url' => '',
            'verify_payment_url' => '',
            'redirect_url' => '',
            'cancel_url' => ''
        ];
    }
}
?>