<?php
require_once 'includes/auth_check.php';
$page = 'users';
require_once '../config/database.php';

// Check if user_id is provided
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
if (!$user_id) {
    $_SESSION['error_message'] = "No user ID provided.";
    header('Location: manage_users.php');
    exit;
}

// Initialize variables
$error = '';
$success = '';
$user = null;

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Fetch user details
try {
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        $_SESSION['error_message'] = "User not found.";
        header('Location: manage_users.php');
        exit;
    }
} catch (PDOException $e) {
    $error = "Database error: " . $e->getMessage();
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate inputs
    $card_holder_name = filter_input(INPUT_POST, 'card_holder_name', FILTER_SANITIZE_STRING);
    $card_type = filter_input(INPUT_POST, 'card_type', FILTER_SANITIZE_STRING);
    $daily_limit = filter_input(INPUT_POST, 'daily_limit', FILTER_VALIDATE_FLOAT);
    $monthly_limit = filter_input(INPUT_POST, 'monthly_limit', FILTER_VALIDATE_FLOAT);
    $online_payments = isset($_POST['online_payments']) ? 1 : 0;
    
    // Validate card type
    $valid_card_types = ['visa', 'mastercard', 'amex'];
    if (!in_array($card_type, $valid_card_types)) {
        $error = "Invalid card type selected.";
    }
    
    // Validate limits
    if ($daily_limit <= 0 || $monthly_limit <= 0) {
        $error = "Spending limits must be greater than zero.";
    }
    
    if (empty($error)) {
        try {
            // Generate card details
            $card_number = generateCardNumber($card_type);
            $expiry_month = rand(1, 12);
            $expiry_year = date('Y') + rand(2, 5); // 2-5 years in the future
            $cvv = generateCVV($card_type);
            
            // Insert new card
            $stmt = $db->prepare("
                INSERT INTO cards 
                (user_id, card_number, card_holder_name, expiry_month, expiry_year, cvv, card_type, 
                status, daily_spending_limit, monthly_spending_limit, online_payments_enabled) 
                VALUES 
                (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)
            ");
            
            $stmt->execute([
                $user_id,
                $card_number,
                $card_holder_name,
                $expiry_month,
                $expiry_year,
                $cvv,
                $card_type,
                $daily_limit,
                $monthly_limit,
                $online_payments
            ]);
            
            // Log the activity
            logAdminActivity($db, "Added new {$card_type} card for user #{$user_id}");
            
            $success = "Card has been successfully added for " . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']);
            
            // Redirect back to user view after short delay
            header("refresh:2;url=view_user.php?id={$user_id}#cards");
        } catch (PDOException $e) {
            $error = "Failed to add card: " . $e->getMessage();
        }
    }
}

// Helper functions
function generateCardNumber($cardType) {
    // Generate card number based on card type
    switch ($cardType) {
        case 'visa':
            $prefix = '4';
            $length = 16;
            break;
        case 'mastercard':
            $prefix = '5' . rand(1, 5);
            $length = 16;
            break;
        case 'amex':
            $prefix = '3' . (rand(0, 1) ? '4' : '7');
            $length = 15;
            break;
        default:
            $prefix = '4';
            $length = 16;
    }
    
    // Generate the remaining digits
    $remainingLength = $length - strlen($prefix);
    $cardNumber = $prefix;
    
    for ($i = 0; $i < $remainingLength - 1; $i++) {
        $cardNumber .= rand(0, 9);
    }
    
    // Add Luhn algorithm check digit
    $cardNumber .= calculateLuhnCheckDigit($cardNumber);
    
    return $cardNumber;
}

function calculateLuhnCheckDigit($number) {
    $sum = 0;
    $numDigits = strlen($number);
    $parity = $numDigits % 2;
    
    for ($i = 0; $i < $numDigits; $i++) {
        $digit = intval($number[$i]);
        
        if ($i % 2 == $parity) {
            $digit *= 2;
            if ($digit > 9) {
                $digit -= 9;
            }
        }
        
        $sum += $digit;
    }
    
    return ($sum * 9) % 10;
}

function generateCVV($cardType) {
    // AMEX uses 4-digit CVV, others use 3-digit
    $length = ($cardType === 'amex') ? 4 : 3;
    $cvv = '';
    
    for ($i = 0; $i < $length; $i++) {
        $cvv .= rand(0, 9);
    }
    
    return $cvv;
}

function logAdminActivity($db, $action) {
    try {
        $admin_id = $_SESSION['admin_id'] ?? 0;
        $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, ip_address, user_agent) VALUES (?, ?, ?, ?)");
        $stmt->execute([$admin_id, $action, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
    } catch (Exception $e) {
        // Silent fail - don't interrupt the main process if logging fails
        error_log("Failed to log admin activity: " . $e->getMessage());
    }
}

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-header-title">Add New Card</h1>
            <p class="text-muted">Create a new card for <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></p>
        </div>

        <!-- Error/Success Messages -->
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bx bx-error-circle me-2"></i>
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($success)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bx bx-check-circle me-2"></i>
                <?php echo $success; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Card Form -->
        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Card Details</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="add_card.php?user_id=<?php echo $user_id; ?>">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="card_holder_name" class="form-label">Card Holder Name</label>
                                    <input type="text" class="form-control" id="card_holder_name" name="card_holder_name" 
                                           value="<?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?>" required>
                                    <small class="text-muted">Name as it will appear on the card</small>
                                </div>
                                <div class="col-md-6">
                                    <label for="card_type" class="form-label">Card Type</label>
                                    <select class="form-select" id="card_type" name="card_type" required>
                                        <option value="visa">Visa</option>
                                        <option value="mastercard">Mastercard</option>
                                        <option value="amex">American Express</option>
                                    </select>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="daily_limit" class="form-label">Daily Spending Limit</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                                        <input type="number" class="form-control" id="daily_limit" name="daily_limit" 
                                               value="1000.00" min="100" step="100" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label for="monthly_limit" class="form-label">Monthly Spending Limit</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                                        <input type="number" class="form-control" id="monthly_limit" name="monthly_limit" 
                                               value="5000.00" min="500" step="500" required>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="online_payments" name="online_payments" checked>
                                    <label class="form-check-label" for="online_payments">Enable Online Payments</label>
                                </div>
                                <small class="text-muted">Allow this card to be used for online transactions</small>
                            </div>

                            <div class="alert alert-info">
                                <i class="bx bx-info-circle me-2"></i>
                                Card number, expiration date, and CVV will be automatically generated.
                            </div>

                            <div class="d-flex justify-content-between mt-4">
                                <a href="view_user.php?id=<?php echo $user_id; ?>#cards" class="btn btn-secondary">Cancel</a>
                                <button type="submit" class="btn btn-primary">Create Card</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Card Preview -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Card Preview</h5>
                    </div>
                    <div class="card-body">
                        <div class="card-container">
                            <div class="card-preview visa" id="cardPreview">
                                <div class="card-chip"></div>
                                <div class="card-logo" id="cardLogo">
                                    <i class="bx bxl-visa"></i>
                                </div>
                                <div class="card-number">XXXX XXXX XXXX XXXX</div>
                                <div class="card-details">
                                    <div>
                                        <small>Card Holder</small>
                                        <div id="previewName"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></div>
                                    </div>
                                    <div>
                                        <small>Expires</small>
                                        <div>MM/YY</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Card Preview Styles */
.card-container {
    perspective: 1000px;
    height: 200px;
    margin-bottom: 1rem;
}

.card-preview {
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 1rem;
    padding: 1.5rem;
    color: white;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    transition: all 0.3s ease;
}

.card-preview.visa {
    background: linear-gradient(135deg, #1a1f71, #5b65d9);
}

.card-preview.mastercard {
    background: linear-gradient(135deg, #000000, #4a4a4a);
}

.card-preview.amex {
    background: linear-gradient(135deg, #006fcf, #65a9e0);
}

.card-chip {
    width: 40px;
    height: 30px;
    background: linear-gradient(135deg, #ffd700, #ffaa00);
    border-radius: 4px;
    margin-bottom: 1rem;
}

.card-logo {
    position: absolute;
    top: 1.5rem;
    right: 1.5rem;
    font-size: 2.5rem;
}

.card-number {
    font-family: 'Courier New', monospace;
    font-size: 1.5rem;
    letter-spacing: 2px;
    text-shadow: 0 1px 2px rgba(0,0,0,0.2);
    margin-bottom: 1rem;
}

.card-details {
    display: flex;
    justify-content: space-between;
    font-size: 0.9rem;
    text-transform: uppercase;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const cardTypeSelect = document.getElementById('card_type');
    const cardPreview = document.getElementById('cardPreview');
    const cardLogo = document.getElementById('cardLogo');
    const cardHolderInput = document.getElementById('card_holder_name');
    const previewName = document.getElementById('previewName');
    
    // Update card preview when card type changes
    cardTypeSelect.addEventListener('change', function() {
        // Remove all classes
        cardPreview.classList.remove('visa', 'mastercard', 'amex');
        
        // Add the selected class
        cardPreview.classList.add(this.value);
        
        // Update logo
        if (this.value === 'visa') {
            cardLogo.innerHTML = '<i class="bx bxl-visa"></i>';
        } else if (this.value === 'mastercard') {
            cardLogo.innerHTML = '<i class="bx bxl-mastercard"></i>';
        } else if (this.value === 'amex') {
            cardLogo.innerHTML = '<i class="bx bxl-american-express"></i>';
        }
    });
    
    // Update card holder name in preview
    cardHolderInput.addEventListener('input', function() {
        previewName.textContent = this.value;
    });
});
</script>

<?php include 'includes/footer.php'; ?>
