<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Check if user is admin
if (!isAdmin($user['id'])) {
    errorResponse('Unauthorized: Admin access required', 403);
}

// Validate action
if (!isset($input['action'])) {
    errorResponse('Action is required', 400);
}

$action = $input['action'];

try {
    switch ($action) {
        case 'list':
            // Get all subscribers with user info and tier name
            $stmt = $pdo->query("
                SELECT s.*, u.email as user_email, t.name as tier_name
                FROM subscribers s
                LEFT JOIN users u ON s.user_id = u.id
                LEFT JOIN subscription_tiers t ON s.subscription_tier_id = t.id
                ORDER BY s.created_at DESC
            ");
            $subscribers = $stmt->fetchAll();
            
            jsonResponse(['subscribers' => $subscribers], 200);
            break;

        case 'update':
            if (!isset($input['id'])) {
                errorResponse('Subscriber ID is required', 400);
            }
            
            $id = $input['id'];
            $subscribed = isset($input['subscribed']) ? (int)$input['subscribed'] : null;
            $tierId = isset($input['subscription_tier_id']) ? (int)$input['subscription_tier_id'] : null;
            $endDate = isset($input['subscription_end']) ? $input['subscription_end'] : null;
            
            $updates = [];
            $params = [];
            
            if ($subscribed !== null) {
                $updates[] = "subscribed = ?";
                $params[] = $subscribed;
            }
            
            if ($tierId !== null) {
                $updates[] = "subscription_tier_id = ?";
                $params[] = $tierId;
            }
            
            if ($endDate !== null) {
                $updates[] = "subscription_end = ?";
                $params[] = $endDate;
            }
            
            if (empty($updates)) {
                errorResponse('No fields to update', 400);
            }
            
            $params[] = $id;
            $sql = "UPDATE subscribers SET " . implode(', ', $updates) . ", updated_at = CURRENT_TIMESTAMP WHERE id = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            jsonResponse(['message' => 'Subscriber updated successfully'], 200);
            break;

        case 'delete':
            if (!isset($input['id'])) {
                errorResponse('Subscriber ID is required', 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM subscribers WHERE id = ?");
            $stmt->execute([$input['id']]);
            
            jsonResponse(['message' => 'Subscriber removed successfully'], 200);
            break;

        case 'tiers':
            $stmt = $pdo->query("SELECT * FROM subscription_tiers ORDER BY id ASC");
            $tiers = $stmt->fetchAll();
            jsonResponse(['tiers' => $tiers], 200);
            break;

        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error managing subscribers: ' . $e->getMessage(), 500);
}
?>
