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


$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
Logger::traceId();
Logger::setContext('user_id', (int)$u['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $bookingId = (int)($_GET['id'] ?? 0);
    if (!$bookingId) Kernel::respond(['error'=>'id_required'],400);
    $bk = db()->prepare('SELECT b.*, u.name AS user_name, p.name AS provider_name, ps.title AS service_title
        FROM bookings b JOIN users u ON u.id=b.user_id JOIN users p ON p.id=b.provider_id
        LEFT JOIN provider_services ps ON ps.id=b.service_id WHERE b.id=? LIMIT 1');
    $bk->execute([$bookingId]);
    $booking = $bk->fetch();
    if (!$booking) Kernel::respond(['error'=>'not_found'],404);
    if ($booking['user_id'] !== $u['id'] && $booking['provider_id'] !== $u['id'])
        Kernel::respond(['error'=>'access_denied'],403);
    Kernel::respond(['success'=>true,'booking'=>$booking]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $b         = json_decode(file_get_contents('php://input'), true) ?? [];
    $bookingId = (int)($b['booking_id'] ?? 0);
    $action    = $b['action'] ?? ''; // start | complete | cancel | list

    if ($action === 'list') {
        $as_provider = (bool)($b['as_provider'] ?? false);
        if ($as_provider) {
            $st = db()->prepare('SELECT b.*, u.name AS user_name, ps.title AS service_title FROM bookings b JOIN users u ON u.id=b.user_id LEFT JOIN provider_services ps ON ps.id=b.service_id WHERE b.provider_id=? ORDER BY b.booking_date DESC LIMIT 50');
            $st->execute([$u['id']]);
        } else {
            $st = db()->prepare('SELECT b.*, p.name AS provider_name, ps.title AS service_title FROM bookings b JOIN users p ON p.id=b.provider_id LEFT JOIN provider_services ps ON ps.id=b.service_id WHERE b.user_id=? ORDER BY b.booking_date DESC LIMIT 50');
            $st->execute([$u['id']]);
        }
        Kernel::respond(['success'=>true,'bookings'=>$st->fetchAll()]);
    }

    // C1 FIX: Cancel booking (user can cancel pending or confirmed)
    if ($action === 'cancel') {
        $bookingId = (int)($b['booking_id'] ?? 0);
        $reason    = mb_substr(trim($b['reason'] ?? ''), 0, 300);
        if (!$bookingId) Kernel::respond(['error'=>'booking_id_required'],400);

        $bk = db()->prepare('SELECT * FROM bookings WHERE id=? AND user_id=? LIMIT 1');
        $bk->execute([$bookingId, $u['id']]);
        $booking = $bk->fetch();
        if (!$booking) Kernel::respond(['error'=>'not_found'],404);
        if (!in_array($booking['status'], ['pending','confirmed']))
            Kernel::respond(['error'=>'cannot_cancel','message'=>'لا يمكن إلغاء حجز في حالة ' . $booking['status']],409);

        db()->prepare(
            "UPDATE bookings SET status='cancelled', cancelled_by='user',
             cancelled_at=NOW(), rejection_reason=? WHERE id=?"
        )->execute([$reason ?: 'إلغاء من المستخدم', $bookingId]);

        // FCM to provider
        $token = get_user_token($booking['provider_id']);
        if ($token) send_push($token, '❌ إلغاء حجز', "ألغى {$u['name']} الحجز بتاريخ {$booking['booking_date']}", ['tag'=>'booking']);
        save_notification($booking['provider_id'], 'booking_cancelled', 'حجز مُلغى', "ألغى {$u['name']} الحجز");

        Kernel::respond(['success'=>true,'message'=>'تم إلغاء الحجز','new_status'=>'cancelled']);
    }

    if (!in_array($action, ['start','complete'])) Kernel::respond(['error'=>'invalid_action'],400);
    $bk = db()->prepare('SELECT * FROM bookings WHERE id=? AND provider_id=? LIMIT 1');
    $bk->execute([$bookingId, $u['id']]);
    $booking = $bk->fetch();
    if (!$booking) Kernel::respond(['error'=>'not_found'],404);

    if ($action === 'start') {
        if ($booking['status'] !== 'confirmed') Kernel::respond(['error'=>'wrong_status'],409);
        db()->prepare("UPDATE bookings SET status='in_progress' WHERE id=?")->execute([$bookingId]);
        $userToken = get_user_token($booking['user_id']);
        if ($userToken) send_push($userToken, '▶️ الخدمة بدأت', 'المزود بدأ تقديم الخدمة', ['tag'=>'booking']);
        Kernel::respond(['success'=>true,'new_status'=>'in_progress']);
    }

    if ($action === 'complete') {
        if ($booking['status'] !== 'in_progress') Kernel::respond(['error'=>'wrong_status'],409);
        try {
            db()->beginTransaction();
            db()->prepare("UPDATE bookings SET status='completed', completed_at=NOW() WHERE id=?")->execute([$bookingId]);
            $gross  = (float)$booking['amount_sdg'];
            $rate   = (float)$booking['commission_rate'];
            $comm   = round($gross * $rate / 100, 2);
            $net    = $gross - $comm;
            db()->prepare('INSERT INTO provider_earnings (provider_id, booking_id, gross_sdg, commission_rate, commission_sdg, net_sdg) VALUES (?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE gross_sdg=VALUES(gross_sdg)')->execute([$u['id'], $bookingId, $gross, $rate, $comm, $net]);
            db()->commit();
        } catch (Throwable $e) {
            db()->rollBack();
            error_log('[booking/status complete] '.$e->getMessage());
            Kernel::respond(['error'=>'server_error'],500);
        }
        $userToken = get_user_token($booking['user_id']);
        if ($userToken) send_push($userToken, '✅ اكتملت الخدمة', 'قيّم تجربتك الآن ⭐', ['tag'=>'booking','booking_id'=>(string)$bookingId]);
        save_notification($booking['user_id'], 'booking_completed', 'اكتملت الخدمة ✅', 'قيّم تجربتك الآن ⭐', ['booking_id'=>(string)$bookingId]);
        Kernel::respond(['success'=>true,'new_status'=>'completed','earnings_net_sdg'=>$net??0]);
    }
}
