<?php

/**
 * ============================================
 * api/tickets/progress.php - UPDATED
 * ============================================
 * Returns reward progress for service-based 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 reward progress for all active service rewards
$query = "SELECT usr.id,
                 usr.service_reward_id,
                 usr.attendance_count,
                 usr.rewards_earned,
                 usr.last_attendance_date,
                 usr.is_redeemed,
                 st.id as service_template_id,
                 st.name as service_name,
                 st.description as service_description,
                 r.id as reward_id,
                 r.name as reward_name,
                 r.description as reward_description,
                 rt.name as reward_type,
                 rt.requires_certificate,
                 sr.attendance_required,
                 sr.start_date,
                 sr.end_date,
                 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
          AND r.is_active = TRUE
          ORDER BY usr.last_attendance_date DESC";

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

// Calculate detailed progress for each reward
foreach ($progress as &$item) {
    // Current progress towards next reward
    $item['current_progress'] = $item['attendance_count'] % $item['attendance_required'];
    if ($item['attendance_required'] > 0) {
        $item['progress_percentage'] = min(100, ($item['attendance_count'] / $item['attendance_required']) * 100);
    } else {
        $item['progress_percentage'] = 0;
    }

    // How many more attendances needed
    $item['remaining_attendances'] = max(0, $item['attendance_required'] - $item['attendance_count']);

    // Status text
    if ($item['is_redeemed']) {
        $item['status'] = 'redeemed';
        $item['status_text'] = 'Reward Redeemed';
    } elseif ($item['is_qualified']) {
        $item['status'] = 'qualified';
        $item['status_text'] = 'Ready to Redeem';
    } else {
        $item['status'] = 'in_progress';
        $item['status_text'] = 'In Progress';
    }

    // Check if reward period is active
    $now = date('Y-m-d H:i:s');
    $item['is_active_period'] = true;
    if ($item['start_date'] && $item['start_date'] > $now) {
        $item['is_active_period'] = false;
    }
    if ($item['end_date'] && $item['end_date'] < $now) {
        $item['is_active_period'] = false;
    }
}

Helpers::sendResponse(true, 'Reward progress retrieved successfully', [
    'progress' => $progress,
    'count' => count($progress),
    'summary' => [
        'total_rewards' => count($progress),
        'qualified' => count(array_filter($progress, function ($p) {
            return $p['is_qualified'] && !$p['is_redeemed'];
        })),
        'redeemed' => count(array_filter($progress, function ($p) {
            return $p['is_redeemed'];
        })),
        'in_progress' => count(array_filter($progress, function ($p) {
            return !$p['is_qualified'] && !$p['is_redeemed'];
        }))
    ]
]);
