<?php
/**
 * MSPE Newsletter Subscription API
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        requireAuth();
        getSubscribers();
        break;
        
    case 'POST':
        subscribe();
        break;
        
    case 'DELETE':
        requireAuth();
        $id = $_GET['id'] ?? null;
        if (!$id) {
            jsonResponse(['success' => false, 'message' => 'Subscriber ID required'], 400);
        }
        unsubscribe($id);
        break;
        
    default:
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

function getSubscribers() {
    global $db;
    
    $subscribers = $db->getAll('subscribers');
    
    // Apply filters
    $status = $_GET['status'] ?? null;
    $limit = (int)($_GET['limit'] ?? 50);
    $offset = (int)($_GET['offset'] ?? 0);
    
    if ($status) {
        $subscribers = array_filter($subscribers, function($s) use ($status) {
            return ($s['status'] ?? 'active') === $status;
        });
    }
    
    // Sort by date (newest first)
    usort($subscribers, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    $total = count($subscribers);
    $subscribers = array_slice(array_values($subscribers), $offset, $limit);
    
    jsonResponse([
        'success' => true,
        'data' => $subscribers,
        'total' => $total,
        'limit' => $limit,
        'offset' => $offset
    ]);
}

function subscribe() {
    global $db;

    requireSameOriginRequest();
    
    $data = getRequestBody();
    
    // Validate email
    $email = $data['email'] ?? '';
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        jsonResponse(['success' => false, 'message' => 'Valid email address required'], 400);
    }
    
    // Check if already subscribed
    $existing = $db->query('subscribers', ['email' => $email]);
    if (!empty($existing)) {
        $subscriber = array_values($existing)[0];
        if (($subscriber['status'] ?? 'active') === 'active') {
            jsonResponse(['success' => true, 'message' => 'You are already subscribed!']);
        } else {
            // Reactivate subscription
            $db->update('subscribers', $subscriber['id'], ['status' => 'active']);
            jsonResponse(['success' => true, 'message' => 'Welcome back! Your subscription has been reactivated.']);
        }
    }
    
    // Create new subscription
    $subscriberData = [
        'email' => sanitize($email),
        'name' => sanitize($data['name'] ?? ''),
        'status' => 'active',
        'source' => $data['source'] ?? 'website'
    ];
    
    $subscriber = $db->insert('subscribers', $subscriberData);
    
    jsonResponse([
        'success' => true,
        'message' => 'Thank you for subscribing! You\'ll receive our latest updates.'
    ], 201);
}

function unsubscribe($id) {
    global $db;
    
    $existing = $db->get('subscribers', $id);
    if (!$existing) {
        jsonResponse(['success' => false, 'message' => 'Subscriber not found'], 404);
    }
    
    // Soft delete by setting status to unsubscribed
    $db->update('subscribers', $id, ['status' => 'unsubscribed']);
    
    jsonResponse([
        'success' => true,
        'message' => 'Successfully unsubscribed'
    ]);
}
