<?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();
}

$card_id = $_GET['id'] ?? null;

if (!$card_id) {
    echo json_encode(['success' => false, 'message' => 'Card ID not provided']);
    exit();
}

try {
    // Get card details
    $stmt = $pdo->prepare("
        SELECT 
            ic.*,
            m.first_name,
            m.last_name,
            m.kso_id,
            m.membership_type,
            m.email,
            m.phone,
            m.address,
            m.photo_url,
            m.date_of_birth,
            CONCAT(m.first_name, ' ', m.last_name) as member_name,
            TIMESTAMPDIFF(YEAR, m.date_of_birth, CURDATE()) as age,
            admin.username as generated_by_name
        FROM id_cards ic
        LEFT JOIN members m ON ic.member_id = m.id
        LEFT JOIN admins admin ON ic.generated_by = admin.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();
    }
    
    // Get card history
    $stmt = $pdo->prepare("
        SELECT 
            ic.*,
            admin.username as generated_by_name,
            'generated' as action_type
        FROM id_cards ic
        LEFT JOIN admins admin ON ic.generated_by = admin.id
        WHERE ic.member_id = ? AND ic.id != ?
        ORDER BY ic.generated_date DESC
    ");
    
    $stmt->execute([$card['member_id'], $card_id]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process card data
    $card_data = [
        'id' => $card['id'],
        'card_number' => $card['card_number'],
        'card_type' => ucfirst(str_replace('_', ' ', $card['card_type'])),
        'template_used' => $card['template_used'],
        'status' => $card['status'],
        'issue_date' => $card['issue_date'],
        'expiry_date' => $card['expiry_date'],
        'generated_date' => $card['generated_date'],
        'qr_code_included' => $card['qr_code_included'],
        'file_path' => $card['file_path'],
        'generated_by' => $card['generated_by_name'],
        'member' => [
            'id' => $card['member_id'],
            'name' => $card['member_name'],
            'kso_id' => $card['kso_id'],
            'membership_type' => $card['membership_type'],
            'email' => $card['email'],
            'phone' => $card['phone'],
            'address' => $card['address'],
            'photo_url' => $card['photo_url'],
            'date_of_birth' => $card['date_of_birth'],
            'age' => $card['age']
        ],
        'is_expired' => (strtotime($card['expiry_date']) < time()),
        'days_until_expiry' => (strtotime($card['expiry_date']) - time()) / (24 * 60 * 60),
        'history' => $history
    ];
    
    echo json_encode([
        'success' => true,
        'card' => $card_data
    ]);
    
} catch (Exception $e) {
    error_log("Card Details Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching card details: ' . $e->getMessage()
    ]);
}
?>
