<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

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

// Verify token
$token = Helpers::getBearerToken();
$userData = Helpers::verifyJWT($token);

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

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

// ✅ Get user's role
$query = "SELECT u.role_id, ur.role_name, ur.role_level
          FROM users u
          JOIN user_roles ur ON u.role_id = ur.id
          WHERE u.id = :user_id AND u.is_active = TRUE";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();

if ($stmt->rowCount() === 0) {
    Helpers::sendResponse(false, 'User not found', null, 404);
}

$userRole = $stmt->fetch(PDO::FETCH_ASSOC);

//
// ✅ Fetch the currently active service occurrence
// Logic: 
//   - Service occurrence is active if NOW() is within
//     1 hour before start_time and 1 hour after end_time.
//
$serviceQuery = "SELECT 
        so.id AS occurrence_id,
        so.service_template_id,
        st.name AS template_name,
        st.description,
        st.location,
        st.latitude,
        st.longitude,
        st.geofence_radius,
        st.is_recurring,
        so.occurrence_date,
        so.start_time,
        so.end_time,
        st.is_active AS template_active,
        so.is_active AS occurrence_active,
        so.was_cancelled,
        st.id AS template_id,
        stt.name AS service_type,
        stt.allows_delegates
    FROM service_occurrences so
    JOIN service_templates st ON so.service_template_id = st.id
    LEFT JOIN service_types stt ON st.service_type_id = stt.id
    WHERE st.is_active = TRUE 
      AND so.is_active = TRUE
      AND so.was_cancelled = FALSE
      AND NOW() BETWEEN DATE_SUB(so.start_time, INTERVAL 1 HOUR)
                    AND DATE_ADD(so.end_time, INTERVAL 1 HOUR)
    ORDER BY so.start_time ASC
    LIMIT 1
";

$serviceStmt = $db->prepare($serviceQuery);
$serviceStmt->execute();

if ($serviceStmt->rowCount() === 0) {
    Helpers::sendResponse(true, 'No active service occurrence available', [
        'service' => null
    ]);
}

$service = $serviceStmt->fetch(PDO::FETCH_ASSOC);

// ✅ Delegate restriction check
if ($userRole['role_name'] === 'delegate' && (empty($service['allows_delegates']) || !$service['allows_delegates'])) {
    Helpers::sendResponse(true, 'No active service available for a delegate', [
        'service' => null
    ]);
}

// ✅ Check if there are rewards tied to this template
$rewardQuery = "
    SELECT COUNT(*) AS reward_count
    FROM service_rewards sr
    WHERE sr.service_template_id = :template_id
      AND sr.is_active = TRUE
      AND (sr.start_date <= NOW() AND (sr.end_date IS NULL OR sr.end_date >= NOW()))
";
$stmt = $db->prepare($rewardQuery);
$stmt->bindParam(':template_id', $service['service_template_id']);
$stmt->execute();

$rewardInfo = $stmt->fetch(PDO::FETCH_ASSOC);
$service['has_rewards'] = $rewardInfo['reward_count'] > 0;

// ✅ Calculate status info
$now = time();
$startTime = strtotime($service['start_time']);
$endTime = strtotime($service['end_time']);

if ($now < $startTime) {
    $service['status'] = 'upcoming';
    $service['starts_in_minutes'] = ceil(($startTime - $now) / 60);
} elseif ($now >= $startTime && $now <= $endTime) {
    $service['status'] = 'ongoing';
    $service['ends_in_minutes'] = ceil(($endTime - $now) / 60);
} else {
    $service['status'] = 'ending_soon';
    $service['grace_period_minutes'] = ceil((($endTime + 3600) - $now) / 60);
}

// ✅ Final Response
Helpers::sendResponse(true, 'Active service occurrence retrieved successfully', [
    'service' => [
        'occurrence_id' => $service['occurrence_id'],
        'service_template_id' => $service['service_template_id'],
        'name' => $service['template_name'],
        'description' => $service['description'],
        'location' => $service['location'],
        'latitude' => $service['latitude'],
        'longitude' => $service['longitude'],
        'geofence_radius' => $service['geofence_radius'],
        'service_type' => $service['service_type'],
        'allows_delegates' => (bool)$service['allows_delegates'],
        'occurrence_date' => $service['occurrence_date'],
        'start_time' => $service['start_time'],
        'end_time' => $service['end_time'],
        'status' => $service['status'],
        'has_rewards' => $service['has_rewards'],
        'time_data' => [
            'starts_in_minutes' => $service['starts_in_minutes'] ?? null,
            'ends_in_minutes' => $service['ends_in_minutes'] ?? null,
            'grace_period_minutes' => $service['grace_period_minutes'] ?? null,
        ],
    ]
]);
