<?php
/**
 * Paystack Webhook Handler
 * This script handles webhook events from Paystack for payment verification and logging
 */

// Get the JSON payload from Paystack
$input = file_get_contents("php://input");
$event = json_decode($input);

// Log all incoming webhooks
log_webhook($input);

// Verify the webhook is from Paystack
$secret_key = 'sk_live_7f111b51a47aa90d451ea8f4311caa76fec83ecb';
$hash = hash('sha512', $input . $secret_key);

// Check if the hash from Paystack matches
if (isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'])) {
    if ($hash !== $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) {
        http_response_code(403);
        echo json_encode(['status' => false, 'message' => 'Invalid signature']);
        exit;
    }
} else {
    // Log warning about missing signature
    log_webhook('WARNING: Missing Paystack signature header', true);
}

// Process the event
if (isset($event->event)) {
    switch ($event->event) {
        case 'charge.success':
            handle_charge_success($event);
            break;
        
        case 'charge.failed':
            handle_charge_failed($event);
            break;
        
        case 'invoice.payment_requested':
            handle_invoice_payment_requested($event);
            break;
        
        case 'transfer.success':
            handle_transfer_success($event);
            break;
        
        case 'transfer.failed':
            handle_transfer_failed($event);
            break;
        
        default:
            log_webhook('Unhandled event type: ' . $event->event, true);
            break;
    }
}

// Return 200 OK response to acknowledge receipt
http_response_code(200);
echo json_encode(['status' => true, 'message' => 'Webhook received']);
exit;

/**
 * Handle successful charge event
 * @param object $event - Paystack event
 */
function handle_charge_success($event) {
    if (isset($event->data)) {
        $data = $event->data;
        
        $transaction = [
            'event' => 'charge.success',
            'reference' => $data->reference,
            'amount' => $data->amount / 100, // Convert from kobo to KES
            'email' => $data->customer->email,
            'status' => $data->status,
            'paid_at' => $data->paid_at,
            'metadata' => isset($data->metadata) ? (array) $data->metadata : [],
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        // Log the successful transaction
        log_transaction($transaction);
        
        // Send confirmation email (optional)
        send_order_confirmation_email($transaction);
    }
}

/**
 * Handle failed charge event
 * @param object $event - Paystack event
 */
function handle_charge_failed($event) {
    if (isset($event->data)) {
        $data = $event->data;
        
        $transaction = [
            'event' => 'charge.failed',
            'reference' => $data->reference,
            'amount' => $data->amount / 100,
            'email' => $data->customer->email,
            'status' => $data->status,
            'gateway_response' => $data->gateway_response,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        log_transaction($transaction);
    }
}

/**
 * Handle invoice payment requested event
 * @param object $event - Paystack event
 */
function handle_invoice_payment_requested($event) {
    if (isset($event->data)) {
        $data = $event->data;
        
        $transaction = [
            'event' => 'invoice.payment_requested',
            'invoice_id' => $data->id,
            'amount' => $data->amount / 100,
            'customer_email' => $data->customer->email,
            'status' => $data->status,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        log_transaction($transaction);
    }
}

/**
 * Handle successful transfer event
 * @param object $event - Paystack event
 */
function handle_transfer_success($event) {
    if (isset($event->data)) {
        $data = $event->data;
        
        $transaction = [
            'event' => 'transfer.success',
            'transfer_code' => $data->transfer_code,
            'amount' => $data->amount / 100,
            'recipient' => $data->recipient,
            'status' => $data->status,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        log_transaction($transaction);
    }
}

/**
 * Handle failed transfer event
 * @param object $event - Paystack event
 */
function handle_transfer_failed($event) {
    if (isset($event->data)) {
        $data = $event->data;
        
        $transaction = [
            'event' => 'transfer.failed',
            'transfer_code' => $data->transfer_code,
            'amount' => $data->amount / 100,
            'recipient' => $data->recipient,
            'status' => $data->status,
            'reason' => $data->reason,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        log_transaction($transaction);
    }
}

/**
 * Send order confirmation email
 * @param array $transaction - Transaction data
 */
function send_order_confirmation_email($transaction) {
    $email = $transaction['email'];
    $subject = "Order Confirmation - Reference: " . $transaction['reference'];
    
    $message = "Thank you for your order!\n\n";
    $message .= "Order Reference: " . $transaction['reference'] . "\n";
    $message .= "Amount Paid: KES " . number_format($transaction['amount'], 2) . "\n";
    $message .= "Payment Status: " . $transaction['status'] . "\n";
    $message .= "Paid At: " . $transaction['paid_at'] . "\n\n";
    $message .= "Your order will be confirmed via WhatsApp shortly.\n";
    $message .= "Thank you for shopping with us!\n";
    
    $headers = "From: guarulhosliquer@gmail.com\r\n";
    $headers .= "Reply-To: guarulhosliquer@gmail.com\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    
    // Send email (uncomment when ready to use)
    // mail($email, $subject, $message, $headers);
}

/**
 * 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);
}

/**
 * Log webhook data
 * @param string $data - Raw webhook data
 * @param bool $is_warning - Whether this is a warning log
 */
function log_webhook($data, $is_warning = false) {
    $log_file = __DIR__ . '/logs/webhooks.log';
    
    // Create logs directory if it doesn't exist
    $log_dir = __DIR__ . '/logs';
    if (!is_dir($log_dir)) {
        mkdir($log_dir, 0755, true);
    }
    
    $timestamp = date('Y-m-d H:i:s');
    $prefix = $is_warning ? '[WARNING]' : '[INFO]';
    $log_entry = "[$timestamp] $prefix $data\n";
    
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}
?>
