<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../../config/database.php';

$db = Database::connect();

$id = $_GET['id'] ?? null;
if (!$id) die('Invalid payment.');

$db->beginTransaction();

$stmt = $db->prepare("
    SELECT * FROM payments
    WHERE id = ?
    FOR UPDATE
");
$stmt->execute([$id]);
$payment = $stmt->fetch();

if (!$payment) die('Payment not found.');

if ($payment['payment_status'] !== 'pending') {
    die('Payment already processed.');
}

/* Update Payment */
$stmt = $db->prepare("
UPDATE payments
SET payment_status = 'paid'
WHERE id = ?
");
$stmt->execute([$payment['id']]);

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

/* Timeline */
$stmt = $db->prepare("
INSERT INTO booking_timeline
(booking_id, status, updated_by)
VALUES (?, 'payment approved', 'admin')
");
$stmt->execute([$payment['booking_id']]);

$db->commit();

header("Location: index.php");
