<?php

/**
 * ============================================
 * api/services/list.php - UPDATED
 * ============================================
 * Lists active service occurrences (upcoming and ongoing)
 */
require_once 'config/database.php';
require_once 'utils/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Helpers::sendResponse(false, 'Method not allowed', null, 405);
}

// Get and verify token
$token = Helpers::getBearerToken();
$userData = Helpers::verifyJWT($token);

if (!$userData) {
    Helpers::sendResponse(false, 'Unauthorized', null, 401);
}

$database = new Database();
$db = $database->getConnection();

// Get all active service occurrences (upcoming and current)
// Changed from `services` to join `service_occurrences` and `service_templates`
$query = "SELECT so.id, 
                 st.name, 
                 st.description, 
                 st.location,
                 so.occurrence_date,
                 so.start_time, 
                 so.end_time,
                 st.service_type_id,
                 stype.name as service_type,
                 st.geofence_radius,
                 st.latitude,
                 st.longitude
          FROM service_occurrences so
          JOIN service_templates st ON so.service_template_id = st.id
          LEFT JOIN service_types stype ON st.service_type_id = stype.id
          WHERE so.is_active = TRUE 
          AND so.was_cancelled = FALSE
          AND so.occurrence_date >= CURDATE()
          ORDER BY so.occurrence_date ASC, so.start_time ASC";

$stmt = $db->prepare($query);
$stmt->execute();
$services = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format the response to match frontend expectations
// Extract time portion from datetime fields
foreach ($services as &$service) {
    $service['id'] = (int)$service['id']; // service_occurrence_id

    // Format start_time and end_time (extract time from datetime)
    if ($service['start_time']) {
        $startDateTime = new DateTime($service['start_time']);
        $service['start_time'] = $startDateTime->format('H:i:s');
    }
    if ($service['end_time']) {
        $endDateTime = new DateTime($service['end_time']);
        $service['end_time'] = $endDateTime->format('H:i:s');
    }
}

Helpers::sendResponse(true, 'Services retrieved successfully', [
    'services' => $services,
    'count' => count($services)
]);
