<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/stripe-php/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

// This is your Stripe webhook secret (get from Stripe Dashboard)
$endpoint_secret = STRIPE_WEBHOOK_SECRET;

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$event = null;

try {
    $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
} catch(\UnexpectedValueException $e) {
    // Invalid payload
    http_response_code(400);
    exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
    // Invalid signature
    http_response_code(400);
    exit();
}

// Handle the event
switch ($event->type) {
    case 'checkout.session.completed':
        $session = $event->data->object;
        
        // Check if payment was successful
        if ($session->payment_status === 'paid') {
            handleSuccessfulPayment($session);
        }
        break;
        
    case 'payment_intent.succeeded':
        $paymentIntent = $event->data->object;
        // Payment succeeded, you can handle additional logic here
        error_log("Payment succeeded: " . $paymentIntent->id);
        break;
        
    case 'payment_intent.payment_failed':
        $paymentIntent = $event->data->object;
        error_log("Payment failed: " . $paymentIntent->id);
        break;
        
    default:
        error_log('Received unknown event type: ' . $event->type);
}

http_response_code(200);

function handleSuccessfulPayment($session) {
    try {
        $umi_id = $session->metadata->umi_id ?? '';
        
        if (!$umi_id) {
            error_log("No UMI ID in session metadata");
            return;
        }
        
        // Retrieve payment intent for more details
        $payment_intent = \Stripe\PaymentIntent::retrieve($session->payment_intent);
        
        // Connect to database
        $mysqli = db_connect();
        
        // Check if payment already recorded
        $check_stmt = $mysqli->prepare("SELECT id FROM paypal_payments WHERE capture_id = ?");
        $check_stmt->bind_param('s', $payment_intent->id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $check_stmt->close();
            $mysqli->close();
            error_log("Payment already recorded: " . $payment_intent->id);
            return;
        }
        $check_stmt->close();
        
        // Insert payment record
        $stmt = $mysqli->prepare("INSERT INTO paypal_payments 
            (umi_id, invoice_no, payment_method, order_id, capture_id, status, payer_email, payer_name, amount, currency, raw_response)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $mysqli->error);
        }
        
        $invoice_no = "RSIS" . $umi_id;
        $method = "stripe";
        $status = $payment_intent->status;
        $payer_email = $session->customer_details->email ?? '';
        $payer_name = $session->customer_details->name ?? '';
        $amount = $session->amount_total / 100; // Convert from cents
        $currency = strtoupper($session->currency);
        
        $raw_response = json_encode([
            'checkout_session' => $session,
            'payment_intent' => $payment_intent
        ]);
        
        $stmt->bind_param(
            'ssssssssdss',
            $umi_id,
            $invoice_no,
            $method,
            $session->id,
            $payment_intent->id,
            $status,
            $payer_email,
            $payer_name,
            $amount,
            $currency,
            $raw_response
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        
        $stmt->close();
        $mysqli->close();
        
        error_log("Payment recorded successfully: " . $payment_intent->id);
        
    } catch (Exception $e) {
        error_log("Error handling successful payment: " . $e->getMessage());
    }
}