<?php

/**
 * ============================================
 * api/tickets/list.php - UPDATED
 * ============================================
 * Now returns user's reward progress (not penalty tickets)
 * The old "tickets" system is now "users_service_rewards"
 */

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 user's reward progress
// Changed from old tickets system to new rewards system
$query = "SELECT usr.id,
                 usr.attendance_count,
                 usr.is_redeemed,
                 usr.redeemed_at,
                 usr.created_at,
                 usr.last_attendance_date,
                 st.name as service_name,
                 r.name as reward_name,
                 r.description as reward_description,
                 rt.name as reward_type,
                 sr.attendance_required,
                 sr.qr_code,
                 CASE 
                    WHEN usr.attendance_count >= sr.attendance_required THEN TRUE
                    ELSE FALSE
                 END as is_qualified
          FROM users_service_rewards usr
          JOIN service_rewards sr ON usr.service_reward_id = sr.id
          JOIN rewards r ON sr.reward_id = r.id
          JOIN reward_types rt ON r.reward_type_id = rt.id
          JOIN service_templates st ON sr.service_template_id = st.id
          WHERE usr.user_id = :user_id
          AND sr.is_active = TRUE
          ORDER BY usr.created_at DESC";

$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();
$rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate progress for each reward
foreach ($rewards as &$reward) {
    $reward['progress_percentage'] = $reward['attendance_required'] > 0
        ? min(100, ($reward['attendance_count'] / $reward['attendance_required']) * 100)
        : 0;
    $reward['remaining_attendances'] = max(0, $reward['attendance_required'] - $reward['attendance_count']);
}

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