<?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,
            m.kso_id,
            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();
    }
    
    // Check if card is active
    if ($card['status'] !== 'active') {
        echo json_encode(['success' => false, 'message' => 'Cannot regenerate inactive card']);
        exit();
    }
    
    // Mark current card as cancelled
    $stmt = $pdo->prepare("UPDATE id_cards SET status = 'cancelled' WHERE id = ?");
    $stmt->execute([$card_id]);
    
    // Generate new card
    $new_card_number = generateCardNumber($card['kso_id']);
    
    $stmt = $pdo->prepare("
        INSERT INTO id_cards (
            member_id,
            card_number,
            card_type,
            template_used,
            issue_date,
            expiry_date,
            status,
            qr_code_included,
            generated_date,
            generated_by
        ) VALUES (?, ?, ?, ?, ?, ?, 'active', ?, NOW(), ?)
    ");
    
    $stmt->execute([
        $card['member_id'],
        $new_card_number,
        $card['card_type'],
        $card['template_used'],
        date('Y-m-d'),
        date('Y-m-d', strtotime('+1 year')),
        $card['qr_code_included'],
        $_SESSION['admin_id']
    ]);
    
    $new_card_id = $pdo->lastInsertId();
    
    // Generate physical card file
    $member_data = [
        'first_name' => $card['first_name'],
        'last_name' => $card['last_name'],
        'kso_id' => $card['kso_id'],
        'photo_url' => null,
        'membership_type' => $card['card_type']
    ];
    
    $card_file = generateCardFile($new_card_id, $member_data, $new_card_number, $card['template_used'], $card['qr_code_included']);
    
    // Update record with file path
    $stmt = $pdo->prepare("UPDATE id_cards SET file_path = ? WHERE id = ?");
    $stmt->execute([$card_file, $new_card_id]);
    
    // Log the activity
    logActivity(
        $_SESSION['admin_id'],
        'id_card_regeneration',
        "Regenerated ID card for {$card['member_name']}",
        ['old_card_id' => $card_id, 'new_card_id' => $new_card_id]
    );
    
    echo json_encode([
        'success' => true,
        'message' => 'ID card regenerated successfully',
        'new_card_id' => $new_card_id,
        'new_card_number' => $new_card_number
    ]);
    
} catch (Exception $e) {
    error_log("ID Card Regeneration Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error regenerating ID card: ' . $e->getMessage()
    ]);
}

function generateCardNumber($kso_id) {
    $year = date('Y');
    $sequence = str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT);
    return "KSO{$year}{$sequence}";
}

function generateCardFile($card_id, $member, $card_number, $template, $include_qr) {
    try {
        // Create cards directory if it doesn't exist
        $cards_dir = '../../../uploads/id-cards/';
        if (!is_dir($cards_dir)) {
            mkdir($cards_dir, 0755, true);
        }
        
        $card_html = generateCardHTML($member, $card_number, $template, $include_qr);
        
        // Save HTML file
        $filename = "card_{$card_id}.html";
        $filepath = $cards_dir . $filename;
        
        file_put_contents($filepath, $card_html);
        
        return "uploads/id-cards/{$filename}";
        
    } catch (Exception $e) {
        error_log("Card File Generation Error: " . $e->getMessage());
        return null;
    }
}

function generateCardHTML($member, $card_number, $template, $include_qr) {
    $member_name = $member['first_name'] . ' ' . $member['last_name'];
    $photo_url = $member['photo_url'] ?? 'dist/img/default-user.png';
    
    $qr_code_html = $include_qr ? "<div class='qr-code'><i class='fas fa-qrcode'></i></div>" : '';
    
    return "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='utf-8'>
        <title>ID Card - {$member_name}</title>
        <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'>
        <style>
            body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
            .id-card {
                width: 320px;
                height: 200px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-radius: 15px;
                padding: 20px;
                color: white;
                position: relative;
                box-shadow: 0 8px 25px rgba(0,0,0,0.15);
                margin: 20px auto;
            }
            .card-header {
                text-align: center;
                font-size: 12px;
                font-weight: bold;
                margin-bottom: 10px;
            }
            .member-info {
                display: flex;
                align-items: center;
                gap: 15px;
            }
            .member-photo {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: #fff;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24px;
                color: #667eea;
            }
            .member-details {
                flex: 1;
            }
            .member-name {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .member-id {
                font-size: 12px;
                opacity: 0.9;
            }
            .card-footer {
                position: absolute;
                bottom: 10px;
                right: 15px;
                font-size: 10px;
                opacity: 0.8;
            }
            .qr-code {
                position: absolute;
                bottom: 10px;
                left: 15px;
                width: 30px;
                height: 30px;
                background: white;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                color: #333;
            }
        </style>
    </head>
    <body>
        <div class='id-card'>
            <div class='card-header'>
                KASHMIRI STUDENTS ORGANIZATION<br>
                CHANDIGARH
            </div>
            <div class='member-info'>
                <div class='member-photo'>
                    <i class='fas fa-user'></i>
                </div>
                <div class='member-details'>
                    <div class='member-name'>{$member_name}</div>
                    <div class='member-id'>ID: {$member['kso_id']}</div>
                    <div class='member-id'>Card: {$card_number}</div>
                </div>
            </div>
            {$qr_code_html}
            <div class='card-footer'>
                Valid Until: " . date('M Y', strtotime('+1 year')) . "
            </div>
        </div>
    </body>
    </html>";
}

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