<?php
session_start();
header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

require_once '../layouts/dbconn.php';

/**
 * Test M-Pesa Daraja API Connection
 * Generates OAuth token to verify credentials
 */

try {
    // Get M-Pesa settings from POST
    $consumer_key = $_POST['mpesa_consumer_key'] ?? '';
    $consumer_secret = $_POST['mpesa_consumer_secret'] ?? '';
    $environment = $_POST['mpesa_environment'] ?? 'sandbox';
    
    if (empty($consumer_key) || empty($consumer_secret)) {
        echo json_encode([
            'success' => false,
            'message' => 'Please provide M-Pesa Consumer Key and Consumer Secret'
        ]);
        exit();
    }
    
    // Determine API URL based on environment
    $auth_url = ($environment === 'production') 
        ? 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
        : 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    
    // Generate OAuth token
    $credentials = base64_encode($consumer_key . ':' . $consumer_secret);
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $auth_url,
        CURLOPT_HTTPHEADER => ['Authorization: Basic ' . $credentials],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($curl);
    curl_close($curl);
    
    if ($curl_error) {
        echo json_encode([
            'success' => false,
            'message' => 'Connection error: ' . $curl_error
        ]);
        exit();
    }
    
    $result = json_decode($response);
    
    if ($http_code === 200 && isset($result->access_token)) {
        // Success - valid credentials
        echo json_encode([
            'success' => true,
            'message' => 'M-Pesa connection successful! Credentials are valid.',
            'environment' => $environment,
            'token_expires_in' => $result->expires_in ?? 3600
        ]);
        
        // Log successful test
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) 
                    VALUES (?, 'TEST_CONNECTION', 'mpesa', 'success', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("is", $_SESSION['user_id'], $_SERVER['REMOTE_ADDR']);
        $log_stmt->execute();
        
    } else {
        // Failed authentication
        $error_message = isset($result->error_description) 
            ? $result->error_description 
            : 'Invalid credentials or API error';
        
        echo json_encode([
            'success' => false,
            'message' => 'M-Pesa authentication failed: ' . $error_message,
            'http_code' => $http_code
        ]);
        
        // Log failed test
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_type, ip_address) 
                    VALUES (?, 'TEST_CONNECTION', 'mpesa', 'failed', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("is", $_SESSION['user_id'], $_SERVER['REMOTE_ADDR']);
        $log_stmt->execute();
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error testing M-Pesa connection: ' . $e->getMessage()
    ]);
}
?>