<?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 {
    // Get POST data
    $template = $_POST['template'] ?? 'standard';
    $members = $_POST['members'] ?? [];
    $issue_date = $_POST['issue_date'] ?? date('Y-m-d');
    $expiry_date = $_POST['expiry_date'] ?? date('Y-m-d', strtotime('+1 year'));
    $include_qr = isset($_POST['include_qr']) ? (bool)$_POST['include_qr'] : true;
    
    if (empty($members)) {
        echo json_encode(['success' => false, 'message' => 'No members selected']);
        exit();
    }
    
    // If "all" is selected, get all members without cards
    if (in_array('all', $members)) {
        $stmt = $pdo->prepare("
            SELECT m.id
            FROM members m
            LEFT JOIN id_cards ic ON m.id = ic.member_id AND ic.status = 'active'
            WHERE ic.id IS NULL
            AND m.status = 'active'
        ");
        $stmt->execute();
        $allMembers = $stmt->fetchAll(PDO::FETCH_COLUMN);
        $members = $allMembers;
    }
    
    $generated_count = 0;
    $errors = [];
    
    foreach ($members as $member_id) {
        try {
            // Get member details
            $stmt = $pdo->prepare("
                SELECT id, first_name, last_name, kso_id, membership_type, photo_url
                FROM members 
                WHERE id = ? AND status = 'active'
            ");
            $stmt->execute([$member_id]);
            $member = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$member) {
                $errors[] = "Member with ID $member_id not found";
                continue;
            }
            
            // Check if member already has an active ID card
            $stmt = $pdo->prepare("
                SELECT id FROM id_cards 
                WHERE member_id = ? AND status = 'active'
            ");
            $stmt->execute([$member_id]);
            $existingCard = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($existingCard) {
                $errors[] = "Member {$member['first_name']} {$member['last_name']} already has an active ID card";
                continue;
            }
            
            // Generate card number
            $card_number = generateCardNumber($member['kso_id']);
            
            // Determine card type based on membership type
            $card_type = determineCardType($member['membership_type']);
            
            // Insert ID card record
            $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([
                $member_id,
                $card_number,
                $card_type,
                $template,
                $issue_date,
                $expiry_date,
                $include_qr ? 1 : 0,
                $_SESSION['admin_id']
            ]);
            
            $card_id = $pdo->lastInsertId();
            
            // Generate physical card file
            $card_file = generateCardFile($card_id, $member, $card_number, $template, $include_qr);
            
            // Update record with file path
            $stmt = $pdo->prepare("UPDATE id_cards SET file_path = ? WHERE id = ?");
            $stmt->execute([$card_file, $card_id]);
            
            $generated_count++;
            
        } catch (Exception $e) {
            $errors[] = "Error generating card for member ID $member_id: " . $e->getMessage();
        }
    }
    
    // Log the generation activity
    logActivity(
        $_SESSION['admin_id'],
        'id_card_generation',
        "Generated $generated_count ID cards",
        ['template' => $template, 'count' => $generated_count]
    );
    
    $response = [
        'success' => true,
        'generated_count' => $generated_count,
        'message' => "$generated_count ID cards generated successfully"
    ];
    
    if (!empty($errors)) {
        $response['errors'] = $errors;
        $response['message'] .= '. Some cards had errors.';
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("ID Card Generation Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error generating ID cards: ' . $e->getMessage()
    ]);
}

function generateCardNumber($kso_id) {
    // Generate card number based on KSO ID
    $year = date('Y');
    $sequence = str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT);
    return "KSO{$year}{$sequence}";
}

function determineCardType($membership_type) {
    switch ($membership_type) {
        case 'individual':
            return 'individual';
        case 'family':
            return 'family_head';
        case 'student':
            return 'student';
        default:
            return 'individual';
    }
}

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);
        }
        
        // For now, we'll create a simple HTML-based card
        // In a production environment, you'd use a proper PDF generation library
        
        $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';
    
    // Generate QR code data
    $qr_data = json_encode([
        'card_number' => $card_number,
        'member_id' => $member['kso_id'],
        'name' => $member_name,
        'type' => 'id_card'
    ]);
    
    $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'>
                KUKI STUDENTS' ORGANISATION<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());
    }
}
?>
