<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
if ($_SERVER['REQUEST_METHOD'] !== 'POST') Kernel::respond(['error'=>'method_not_allowed'],405);

$b         = json_decode(file_get_contents('php://input'), true) ?? [];
$bookingId = (int)($b['booking_id'] ?? 0);
$action    = $b['action'] ?? '';
$reason    = mb_substr(trim($b['rejection_reason'] ?? ''), 0, 300);

if (!$bookingId || !in_array($action, ['confirm','reject']))
    Kernel::respond(['error'=>'invalid_input'],400);

if ($action === 'reject' && !$reason)
    Kernel::respond(['error'=>'reason_required'],400);

try {
    // تحقق من وجود الحجز
    $bk = db()->prepare("SELECT * FROM bookings WHERE id=? LIMIT 1");
    $bk->execute([$bookingId]);
    $booking = $bk->fetch();
    if (!$booking) Kernel::respond(['error'=>'booking_not_found'],404);

    // BRIDGE: ownership enforcement
    // Only the booking user (to cancel) or the provider (to confirm/reject) can act
    $isBookingUser   = ((int)$booking['user_id'] === (int)$u['id']);
    $isBookingProvider = ((int)$booking['provider_id'] === (int)$u['id']);
    if (!$isBookingUser && !$isBookingProvider) {
        Logger::warn('booking_confirm_unauthorized', [
            'booking_id' => $bookingId,
            'action'     => $action,
        ]);
        Kernel::respond(['error' => 'forbidden', 'message' => 'ليس لديك صلاحية تعديل هذا الحجز'], 403);
    }

    $newStatus = $action === 'confirm' ? 'confirmed' : 'cancelled';
    db()->prepare("UPDATE bookings SET status=?,updated_at=NOW() WHERE id=?")
       ->execute([$newStatus, $bookingId]);

    // ── إشعار للمستخدم ────────────────────────────────────────
    try {
        $title = $action === 'confirm' ? '✅ تم تأكيد حجزك' : '❌ تم إلغاء حجزك';
        $body  = $action === 'confirm'
            ? 'حجزك تم تأكيده. ' . ($booking['service_type'] ?? '') . ' — ' . ($booking['slot_time'] ?? '')
            : 'تم إلغاء حجزك. السبب: ' . ($reason ?: 'لم يُحدَّد');

        db()->prepare(
            "INSERT INTO notifications (user_id, type, title, body, data)
             VALUES (?, ?, ?, ?, ?)"
        )->execute([
            $booking['user_id'],
            'booking_' . $action,
            $title,
            $body,
            json_encode(['booking_id' => $bookingId]),
        ]);
    } catch (Throwable $notifErr) {
        error_log("[booking/confirm] notif: " . $notifErr->getMessage());
    }

    // ── إذا إلغاء — أعِد الرصيد ──────────────────────────────
    if ($action === 'reject' && !empty($booking['amount_sdg'])) {
        try {
            require_once __DIR__ . '/../../engine/BillingEngine.php';
            BillingEngine::rollbackFunds(
                (int)$booking['user_id'],
                (float)$booking['amount_sdg'],
                $booking['service_type'] ?? 'general'
            );
            Logger::info('booking_refund', [
                'booking_id' => $bookingId,
                'user_id'    => (int)$booking['user_id'],
                'amount_sdg' => (float)$booking['amount_sdg'],
            ]);
        } catch (Throwable $refundErr) {
            Logger::warn('booking_refund_failed', ['booking_id' => $bookingId, 'error' => $refundErr->getMessage()]);
        }
    }

    Logger::info('booking_confirmed', [
        'booking_id' => $bookingId,
        'action'     => $action,
        'new_status' => $newStatus,
    ]);
    Kernel::respond(['ok' => true, 'status' => $newStatus, 'booking_id' => $bookingId,
                   'trace_id' => Logger::traceId()]);

} catch (Throwable $e) {
    Logger::error('booking_confirm_failed', ['booking_id' => $bookingId, 'action' => $action, 'error' => $e->getMessage()]);
    http_response_code(500);
    echo json_encode(['error' => 'action_failed', 'message' => 'فشلت العملية — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
