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

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

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

// Get admin token from headers
$admin_token = isset($_SERVER['HTTP_ADMIN_TOKEN']) ? $_SERVER['HTTP_ADMIN_TOKEN'] : '';

// Authenticate admin
authenticateAdmin($admin_token);

$conn = getDbConnection();

if ($method === 'GET') {
    // Optional filters
    $user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    $status = isset($_GET['status']) ? $_GET['status'] : '';

    // Build the query with optional filters
    $query = "SELECT rh.id, rh.user_id, rh.subcategory_id, rh.image_url, rh.gift_code, rh.status, rh.rejection_reason, rh.created_at, 
                     u.email, roc.category_name, ros.sub_category_name, ros.coins, ros.cash
              FROM redeem_history rh
              JOIN users u ON rh.user_id = u.id
              JOIN redeem_options_subcategories ros ON rh.subcategory_id = ros.id
              JOIN redeem_options_categories roc ON ros.category_id = roc.id
              WHERE 1=1";
    
    $params = [];
    $types = '';

    if ($user_id > 0) {
        $query .= " AND rh.user_id = ?";
        $params[] = $user_id;
        $types .= 'i';
    }

    if (!empty($status) && in_array($status, ['pending', 'approved', 'rejected'])) {
        $query .= " AND rh.status = ?";
        $params[] = $status;
        $types .= 's';
    }

    $query .= " ORDER BY rh.created_at DESC";

    if (!empty($params)) {
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $conn->query($query);
    }

    $history = [];
    while ($row = $result->fetch_assoc()) {
        $history[] = [
            'id' => $row['id'],
            'user_id' => $row['user_id'],
            'user_email' => $row['email'],
            'redeem_option_name' => $row['category_name'] . ' - ' . $row['sub_category_name'],
            'image_url' => $row['image_url'],
            'gift_code' => $row['gift_code'],
            'status' => $row['status'],
            'rejection_reason' => $row['rejection_reason'],
            'created_at' => $row['created_at'],
            'coins' => (int)$row['coins'],
            'cash' => (float)$row['cash']
        ];
    }

    if (isset($stmt)) $stmt->close();
    sendResponse(200, 'Redeem history fetched', ['history' => $history]);
} elseif ($method === 'PUT') {
    // 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');
    }

    if (!$data || !isset($data['history_id']) || !isset($data['status'])) {
        sendResponse(400, 'Missing history_id or status');
    }

    $history_id = (int)$data['history_id'];
    $status = $data['status'];
    $gift_code = isset($data['gift_code']) ? trim($data['gift_code']) : null;
    $rejection_reason = isset($data['rejection_reason']) ? trim($data['rejection_reason']) : null;

    // Validate status
    if (!in_array($status, ['pending', 'approved', 'rejected'])) {
        sendResponse(400, 'Invalid status. Must be pending, approved, or rejected');
    }

    // Validate gift_code for approved status
    if ($status === 'approved') {
        if (empty($gift_code) || strlen($gift_code) < 5) {
            sendResponse(400, 'Gift code required for approved status and must be at least 5 characters');
        }
    } else {
        $gift_code = null; // Clear gift_code if not approved
    }

    // Validate rejection_reason for rejected status
    if ($status === 'rejected') {
        if (empty($rejection_reason) || strlen($rejection_reason) < 10) {
            sendResponse(400, 'Rejection reason required for rejected status and must be at least 10 characters');
        }
    } else {
        $rejection_reason = null; // Clear rejection_reason if not rejected
    }

    // Fetch current status to prevent redundant updates
    $stmt = $conn->prepare("SELECT status FROM redeem_history WHERE id = ?");
    $stmt->bind_param("i", $history_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $stmt->close();
        sendResponse(400, 'Redeem history entry not found');
    }

    $current = $result->fetch_assoc();
    if ($current['status'] === $status) {
        $stmt->close();
        sendResponse(400, 'Status is already ' . $status);
    }

    // Update the redeem history entry
    $stmt = $conn->prepare("UPDATE redeem_history SET status = ?, gift_code = ?, rejection_reason = ? WHERE id = ?");
    $stmt->bind_param("sssi", $status, $gift_code, $rejection_reason, $history_id);
    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        $stmt->close();
        sendResponse(400, 'Failed to update redeem history entry');
    }

    $stmt->close();
    sendResponse(200, 'Redeem history updated successfully');
} else {
    sendResponse(405, 'Method not allowed');
}

$conn->close();
?>