<?php

/**
 * api/tickets/redeem.php - UPDATED
 * Redeems a qualified reward
 */
require_once 'config/database.php';
require_once 'utils/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    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 request data
$data = json_decode(file_get_contents("php://input"));

if (empty($data->reward_progress_id)) {
    Helpers::sendResponse(false, 'Reward progress ID is required', null, 400);
}

try {
    $db->beginTransaction();

    // Get reward progress details
    $query = "SELECT usr.id, usr.user_id, usr.attendance_count, usr.is_redeemed,
                     sr.attendance_required, sr.reward_id,
                     r.name as reward_name,
                     rt.requires_certificate
              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
              WHERE usr.id = :progress_id
              AND usr.user_id = :user_id
              FOR UPDATE";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':progress_id', $data->reward_progress_id);
    $stmt->bindParam(':user_id', $userData['user_id']);
    $stmt->execute();

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

    if (!$progress) {
        $db->rollBack();
        Helpers::sendResponse(false, 'Reward progress not found', null, 404);
    }

    // Check if already redeemed
    if ($progress['is_redeemed']) {
        $db->rollBack();
        Helpers::sendResponse(false, 'Reward has already been redeemed', null, 400);
    }

    // Check if qualified
    if ($progress['attendance_count'] < $progress['attendance_required']) {
        $db->rollBack();
        Helpers::sendResponse(false, 'Insufficient attendance. You need ' .
            ($progress['attendance_required'] - $progress['attendance_count']) .
            ' more attendance(s) to qualify', null, 400);
    }

    // Mark as redeemed (admin will process the actual redemption)
    $updateQuery = "UPDATE users_service_rewards 
                    SET is_redeemed = TRUE,
                        redeemed_at = NOW(),
                        updated_at = NOW()
                    WHERE id = :progress_id";

    $stmt = $db->prepare($updateQuery);
    $stmt->bindParam(':progress_id', $data->reward_progress_id);
    $stmt->execute();

    $db->commit();

    Helpers::sendResponse(true, 'Reward redemption request submitted successfully. An admin will process your reward.', [
        'reward_name' => $progress['reward_name'],
        'redeemed_at' => date('Y-m-d H:i:s'),
        'requires_certificate' => (bool)$progress['requires_certificate']
    ], 200);
} catch (PDOException $e) {
    $db->rollBack();
    error_log("Redeem error: " . $e->getMessage());
    Helpers::sendResponse(false, 'Failed to process redemption request', null, 500);
} catch (Exception $e) {
    $db->rollBack();
    error_log("Redeem error: " . $e->getMessage());
    Helpers::sendResponse(false, 'An error occurred', null, 500);
}
