<?php
/**
 * GET /api/booking/provider_list.php
 * WAVE E — Full Kernel Replace
 * Provider's bookings list
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];

if (!($u['provider_verified'] ?? false)) {
    Kernel::fail('not_verified', 'يجب التحقق من حسابك كمزود', 403);
}

$limit  = min(50, max(1, (int)($_GET['limit'] ?? 20)));
$offset = max(0, (int)($_GET['offset'] ?? 0));
$status = $_GET['status'] ?? 'all';
$valid  = ['pending','confirmed','in_progress','completed','cancelled','all'];
if (!in_array($status, $valid)) $status = 'all';

try {
    $where = $status === 'all' ? '' : "AND b.status = :status";
    $q = db()->prepare("
        SELECT b.id, b.booking_date, b.booking_time, b.status, b.amount_sdg,
               b.consultation_type, b.notes, b.created_at,
               u.name AS user_name, u.id AS user_id,
               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 = :pid {$where}
        ORDER BY b.booking_date DESC, b.booking_time DESC
        LIMIT :lim OFFSET :off
    ");
    $params = [':pid' => $u['id'], ':lim' => $limit, ':off' => $offset];
    if ($status !== 'all') $params[':status'] = $status;
    $q->execute($params);
    $bookings = $q->fetchAll(PDO::FETCH_ASSOC);

    $stats = db()->prepare("
        SELECT COUNT(*) total,
               SUM(status='completed') completed,
               SUM(status='pending') pending,
               COALESCE(SUM(CASE WHEN status='completed' THEN amount_sdg ELSE 0 END), 0) total_revenue
        FROM bookings WHERE provider_id=?
    ");
    $stats->execute([$u['id']]);
    $statsRow = $stats->fetch(PDO::FETCH_ASSOC);

    Kernel::respond(['bookings' => $bookings, 'stats' => $statsRow]);

} catch (Throwable $e) {
    Logger::error('provider_bookings_failed', ['provider_id' => $u['id'], 'error' => $e->getMessage()]);
    Kernel::fail('fetch_failed', 'تعذّر تحميل الحجوزات', 500);
}
