<?php

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/vendor/autoload.php';

use Stripe\Webhook;
use Stripe\Exception\SignatureVerificationException;

$db = Database::connect();

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$endpoint_secret = $_ENV['STRIPE_WEBHOOK_SECRET'];

try {
    $event = Webhook::constructEvent(
        $payload,
        $sig_header,
        $endpoint_secret
    );
} catch (SignatureVerificationException $e) {
    http_response_code(400);
    exit();
}

if ($event->type === 'checkout.session.completed') {

    $session = $event->data->object;
    $booking_id = $session->metadata->booking_id;

    $db->beginTransaction();

    /*
    |--------------------------------------------------------------------------
    | Mark Payment Paid
    |--------------------------------------------------------------------------
    */

    $stmt = $db->prepare("
        UPDATE payments
        SET payment_status = 'paid'
        WHERE transaction_reference = ?
    ");
    $stmt->execute([$session->id]);

    /*
    |--------------------------------------------------------------------------
    | Complete Booking
    |--------------------------------------------------------------------------
    */

    $stmt = $db->prepare("
        UPDATE bookings
        SET status = 'completed'
        WHERE id = ?
    ");
    $stmt->execute([$booking_id]);

    /*
    |--------------------------------------------------------------------------
    | Timeline
    |--------------------------------------------------------------------------
    */

    $stmt = $db->prepare("
        INSERT INTO booking_timeline
        (booking_id, status, updated_by)
        VALUES (?, 'payment confirmed (stripe)', 'system')
    ");
    $stmt->execute([$booking_id]);

    $db->commit();
}

http_response_code(200);
