<?php

/**
 * ============================================
 * api/tickets/stats.php - NEW
 * ============================================
 * Returns statistics about user's rewards progress
 */

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 total rewards qualified for
$query = "SELECT COUNT(*) as total
          FROM users_service_rewards usr
          JOIN service_rewards sr ON usr.service_reward_id = sr.id
          WHERE usr.user_id = :user_id
          AND usr.attendance_count >= sr.attendance_required
          AND usr.is_redeemed = FALSE
          AND sr.is_active = TRUE";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();
$qualifiedCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Get total rewards redeemed
$query = "SELECT COUNT(*) as total
          FROM users_service_rewards
          WHERE user_id = :user_id
          AND is_redeemed = TRUE";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();
$redeemedCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Get total active rewards user is tracking
$query = "SELECT COUNT(*) as total
          FROM users_service_rewards usr
          JOIN service_rewards sr ON usr.service_reward_id = sr.id
          WHERE usr.user_id = :user_id
          AND sr.is_active = TRUE";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();
$activeCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

// Get certificates earned
$query = "SELECT COUNT(*) as total
          FROM certificates
          WHERE user_id = :user_id";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $userData['user_id']);
$stmt->execute();
$certificatesCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

Helpers::sendResponse(true, 'Reward statistics retrieved successfully', [
    'stats' => [
        'qualified_rewards' => (int)$qualifiedCount,
        'redeemed_rewards' => (int)$redeemedCount,
        'active_rewards' => (int)$activeCount,
        'certificates_earned' => (int)$certificatesCount
    ]
]);
