<?php
/**
 * Paystack Callback Handler
 * This script handles payment verification when user is redirected back from Paystack
 */

// Load configuration
require_once 'config.php';

// Get the payment reference from URL
$reference = isset($_GET['reference']) ? sanitize_input($_GET['reference']) : null;

if (!$reference) {
    http_response_code(400);
    echo json_encode(['status' => false, 'message' => 'No payment reference provided']);
    exit;
}

// Verify payment with Paystack
$verification_result = verify_payment($reference);

if ($verification_result['status']) {
    // Payment verified successfully
    $payment_data = $verification_result['data'];
    
    // Log the transaction
    log_transaction([
        'reference' => $reference,
        'amount' => $payment_data['amount'],
        'email' => $payment_data['customer']['email'],
        'status' => 'completed',
        'metadata' => $payment_data['metadata'],
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
    // Respond with success
    http_response_code(200);
    echo json_encode([
        'status' => true,
        'message' => 'Payment verified successfully',
        'reference' => $reference,
        'amount' => $payment_data['amount'],
        'email' => $payment_data['customer']['email']
    ]);
    exit;
} else {
    // Payment verification failed
    log_transaction([
        'reference' => $reference,
        'status' => 'failed',
        'error' => $verification_result['message'],
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
    http_response_code(400);
    echo json_encode([
        'status' => false,
        'message' => 'Payment verification failed: ' . $verification_result['message']
    ]);
    exit;
}

/**
 * Verify payment with Paystack API
 * @param string $reference - Payment reference
 * @return array - Verification result
 */
function verify_payment($reference) {
    $secret_key = 'sk_live_7f111b51a47aa90d451ea8f4311caa76fec83ecb';
    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer " . $secret_key,
            "Cache-Control: no-cache",
        ),
    ));
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if ($err) {
        return [
            'status' => false,
            'message' => 'CURL Error: ' . $err
        ];
    }
    
    $result = json_decode($response, true);
    
    if (isset($result['status']) && $result['status'] === true) {
        return [
            'status' => true,
            'data' => $result['data']
        ];
    } else {
        return [
            'status' => false,
            'message' => isset($result['message']) ? $result['message'] : 'Unknown error'
        ];
    }
}

/**
 * Sanitize input
 * @param string $input - Input string
 * @return string - Sanitized string
 */
function sanitize_input($input) {
    return htmlspecialchars(stripslashes(trim($input)), ENT_QUOTES, 'UTF-8');
}

/**
 * Log transaction
 * @param array $data - Transaction data
 */
function log_transaction($data) {
    $log_file = __DIR__ . '/logs/transactions.log';
    
    // Create logs directory if it doesn't exist
    $log_dir = __DIR__ . '/logs';
    if (!is_dir($log_dir)) {
        mkdir($log_dir, 0755, true);
    }
    
    $log_entry = json_encode($data) . "\n";
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}
?>
