<?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_id = $_POST['id'] ?? null;
    
    if (!$card_id) {
        echo json_encode(['success' => false, 'message' => 'Card ID not provided']);
        exit();
    }
    
    // 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 = ?
    ");
    
    $stmt->execute([$card_id]);
    $card = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$card) {
        echo json_encode(['success' => false, 'message' => 'Card not found']);
        exit();
    }
    
    // Update card status to cancelled
    $stmt = $pdo->prepare("UPDATE id_cards SET status = 'cancelled' WHERE id = ?");
    $stmt->execute([$card_id]);
    
    // Log the activity
    logActivity(
        $_SESSION['admin_id'],
        'id_card_cancellation',
        "Cancelled ID card for {$card['member_name']}",
        ['card_id' => $card_id, 'card_number' => $card['card_number']]
    );
    
    echo json_encode([
        'success' => true,
        'message' => 'ID card cancelled successfully'
    ]);
    
} catch (Exception $e) {
    error_log("ID Card Cancellation Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error cancelling ID card: ' . $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());
    }
}
?>
