<?php
require_once '../middleware.php';

header('Content-Type: application/json');

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Get headers for authentication
$device_id = isset($_SERVER['HTTP_DEVICE_ID']) ? $_SERVER['HTTP_DEVICE_ID'] : '';
$session_token = isset($_SERVER['HTTP_SESSION_TOKEN']) ? $_SERVER['HTTP_SESSION_TOKEN'] : '';

if ($method !== 'POST') {
    sendResponse(405, 'Method not allowed');
}

// Get the encrypted payload
$encrypted_payload = file_get_contents('php://input');
if (empty($encrypted_payload)) {
    sendResponse(400, 'Empty request body');
}

// Decrypt the payload
$data = decryptRequestPayload($encrypted_payload);
if (!$data) {
    sendResponse(400, 'Invalid request body');
}

$user_id = isset($data['user_id']) ? (int)$data['user_id'] : 0;

if ($user_id <= 0) {
    sendResponse(400, 'Invalid user_id');
}

// Authenticate the user session
authenticateSession($user_id, $device_id, $session_token);
rateLimit($user_id);

$conn = getDbConnection();

// Fetch redeem history for the user
$query = "SELECT rh.id, rh.subcategory_id, rh.image_url, rh.gift_code, rh.pin, rh.status, rh.rejection_reason, rh.created_at, 
                 roc.category_name, ros.sub_category_name, ros.cash
          FROM redeem_history rh
          JOIN redeem_options_subcategories ros ON rh.subcategory_id = ros.id
          JOIN redeem_options_categories roc ON ros.category_id = roc.id
          WHERE rh.user_id = ?
          ORDER BY rh.created_at DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

$history = [];
while ($row = $result->fetch_assoc()) {
    // Format created_at as DD/MM/YYYY h:i A
    $created_at = $row['created_at'];
    $date = $created_at ? date('d/m/Y', strtotime($created_at)) : '';
    $time = $created_at ? date('h:i A', strtotime($created_at)) : '';
    $formatted_created_at = $date && $time ? ($date . ' ' . $time) : '';

    $history[] = [
        'id' => $row['id'],
        'redeem_option_name' => $row['category_name'] . ' - ' . $row['sub_category_name'],
        'image_url' => $row['image_url'],
        'gift_code' => $row['gift_code'],
        'pin' => $row['pin'],
        'status' => $row['status'],
        'rejection_reason' => $row['rejection_reason'],
        'cash' => $row['cash'], // ✅ Added cash field here
        'created_at' => $formatted_created_at
    ];
}

$stmt->close();
$conn->close();

$new_session_token = generateNewSessionToken($user_id, $device_id);
sendResponse(200, 'Redeem history fetched', ['history' => $history], $new_session_token);
?>