<?php
require_once '../config.php';
require_once '../auth/check_auth.php';

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

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $card_ids = $_POST['ids'] ?? [];
    
    if (empty($card_ids)) {
        echo json_encode(['success' => false, 'message' => 'No cards selected']);
        exit();
    }
    
    $placeholders = str_repeat('?,', count($card_ids) - 1) . '?';
    
    // Get card details
    $stmt = $pdo->prepare("
        SELECT 
            ic.*,
            m.first_name,
            m.last_name,
            CONCAT(m.first_name, ' ', m.last_name) as member_name
        FROM id_cards ic
        LEFT JOIN members m ON ic.member_id = m.id
        WHERE ic.id IN ($placeholders)
    ");
    
    $stmt->execute($card_ids);
    $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($cards)) {
        echo json_encode(['success' => false, 'message' => 'No cards found']);
        exit();
    }
    
    $cancelled_count = 0;
    
    foreach ($cards as $card) {
        // Update card status to cancelled
        $stmt = $pdo->prepare("UPDATE id_cards SET status = 'cancelled' WHERE id = ?");
        $stmt->execute([$card['id']]);
        $cancelled_count++;
    }
    
    // Log the activity
    logActivity(
        $_SESSION['admin_id'],
        'bulk_id_card_cancellation',
        "Cancelled $cancelled_count ID cards",
        ['card_ids' => $card_ids, 'cancelled_count' => $cancelled_count]
    );
    
    echo json_encode([
        'success' => true,
        'message' => "$cancelled_count ID cards cancelled successfully",
        'cancelled_count' => $cancelled_count
    ]);
    
} catch (Exception $e) {
    error_log("Bulk ID Card Cancellation Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error cancelling ID cards: ' . $e->getMessage()
    ]);
}

function logActivity($admin_id, $action, $description, $details = []) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO activity_logs (admin_id, action, description, details, created_at)
            VALUES (?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $admin_id,
            $action,
            $description,
            json_encode($details)
        ]);
    } catch (Exception $e) {
        error_log("Activity Log Error: " . $e->getMessage());
    }
}
?>
