<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'cards';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';

// --- UNIFIED LOGIC FOR ALL CARD ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['link_external_card'])) {
        // Handle external card linking
        $card_number = preg_replace('/\D/', '', $_POST['card_number']);
        $card_holder = filter_input(INPUT_POST, 'card_holder_name', FILTER_SANITIZE_STRING);
        $expiry_month = filter_input(INPUT_POST, 'expiry_month', FILTER_VALIDATE_INT);
        $expiry_year = filter_input(INPUT_POST, 'expiry_year', FILTER_VALIDATE_INT);
        $cvv = filter_input(INPUT_POST, 'cvv', FILTER_SANITIZE_STRING);
        $card_type = filter_input(INPUT_POST, 'card_type', FILTER_SANITIZE_STRING);
        
        // Validate inputs
        $errors = [];
        if (strlen($card_number) < 13 || strlen($card_number) > 19) {
            $errors[] = "Invalid card number.";
        }
        if (empty($card_holder)) {
            $errors[] = "Card holder name is required.";
        }
        if ($expiry_month < 1 || $expiry_month > 12) {
            $errors[] = "Invalid expiry month.";
        }
        if ($expiry_year < date('Y')) {
            $errors[] = "Card has expired.";
        }
        if (strlen($cvv) < 3 || strlen($cvv) > 4) {
            $errors[] = "Invalid CVV.";
        }
        if (!in_array($card_type, ['visa', 'mastercard', 'amex'])) {
            $errors[] = "Invalid card type.";
        }
        
        if (empty($errors)) {
            try {
                // Check if external_cards table exists
                try {
                    // Check if card already exists
                    $check_stmt = $db->prepare("SELECT id FROM external_cards WHERE card_number = ? AND user_id = ?");
                    $check_stmt->execute([encrypt_card_number($card_number), $_SESSION['user_id']]);
                    if ($check_stmt->rowCount() > 0) {
                        $error_message = "This card is already linked to your account.";
                    } else {
                        // Insert the new external card
                        $insert_stmt = $db->prepare("
                            INSERT INTO external_cards 
                            (user_id, card_number, card_holder_name, expiry_month, expiry_year, cvv, card_type, status) 
                            VALUES 
                            (?, ?, ?, ?, ?, ?, ?, 'active')
                        ");
                        $insert_stmt->execute([
                            $_SESSION['user_id'],
                            encrypt_card_number($card_number),
                            $card_holder,
                            $expiry_month,
                            $expiry_year,
                            encrypt_cvv($cvv),
                            $card_type
                        ]);
                        
                        $success_message = "External card has been linked successfully.";
                    }
                } catch (PDOException $e) {
                    // If table doesn't exist
                    $error_message = "External card linking is not available at this time.";
                    error_log("External_cards table error: " . $e->getMessage());
                }
            } catch (Exception $e) {
                $error_message = "An error occurred while linking the card.";
                error_log("External Card Linking Error: " . $e->getMessage());
            }
        } else {
            $error_message = implode("<br>", $errors);
        }
    } 
    // Handle external card unlinking/deletion
    elseif (isset($_POST['unlink_card']) && isset($_POST['ext_card_id'])) {
        $ext_card_id = filter_input(INPUT_POST, 'ext_card_id', FILTER_VALIDATE_INT);
        $user_id = $_SESSION['user_id'];
        
        if (!$ext_card_id) {
            $error_message = "Invalid card information.";
        } else {
            try {
                // Verify the card belongs to the user
                $check_stmt = $db->prepare("SELECT id FROM external_cards WHERE id = ? AND user_id = ?");
                $check_stmt->execute([$ext_card_id, $user_id]);
                
                if ($check_stmt->rowCount() === 0) {
                    $error_message = "Security Error: You do not have permission to unlink this card.";
                } else {
                    // Delete the external card
                    $delete_stmt = $db->prepare("DELETE FROM external_cards WHERE id = ?");
                    if ($delete_stmt->execute([$ext_card_id])) {
                        $success_message = "External card has been successfully unlinked.";
                    } else {
                        $error_message = "Failed to unlink the card. Please try again.";
                    }
                }
            } catch (PDOException $e) {
                $error_message = "An error occurred while unlinking the card.";
                error_log("External Card Unlinking Error: " . $e->getMessage());
            }
        }
    }
    // Handle regular card actions
    elseif (isset($_POST['card_id'])) {
        $card_id = $_POST['card_id'];
        $user_id = $_SESSION['user_id'];

        if (empty($card_id) || empty($user_id)) {
            $error_message = "Action failed: Missing critical information. Please refresh and try again.";
        } else {
            $stmt = $db->prepare("SELECT id, status FROM cards WHERE id = ? AND user_id = ?");
            $stmt->execute([$card_id, $user_id]);
            $card = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$card) {
                $error_message = "Security Error: You do not have permission to modify this card.";
            } else {
                if (isset($_POST['toggle_freeze'])) {
                    $new_status = ($card['status'] == 'active') ? 'frozen' : 'active';
                    $update_stmt = $db->prepare("UPDATE cards SET status = ? WHERE id = ?");
                    if ($update_stmt->execute([$new_status, $card_id])) {
                        $success_message = "Card has been successfully " . ($new_status == 'active' ? 'unfrozen' : 'frozen') . ".";
                    }
                }
                elseif (isset($_POST['delete_card'])) {
                    $delete_stmt = $db->prepare("DELETE FROM cards WHERE id = ?");
                    if ($delete_stmt->execute([$card_id])) {
                        $success_message = "Card has been successfully removed.";
                    }
                }
            }
        }
    } else {
        $error_message = "Invalid request. Please refresh the page and try again.";
    }
}

// Check for success message from add-card.php
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

// Fetch all cards for the logged-in user
$stmt = $db->prepare("SELECT * FROM cards WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$cards = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch external cards if the table exists
try {
    $ext_stmt = $db->prepare("SELECT * FROM external_cards WHERE user_id = ? ORDER BY created_at DESC");
    $ext_stmt->execute([$_SESSION['user_id']]);
    $external_cards = $ext_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $external_cards = [];
}

function formatCardNumber($number) {
    return implode(' ', str_split($number, 4));
}

// Helper functions for card encryption (implement these properly in production)
function encrypt_card_number($number) {
    // In production, use proper encryption
    return 'XXXXXXXXXXXX' . substr($number, -4);
}

function encrypt_cvv($cvv) {
    // In production, use proper encryption
    return '***';
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* My Cards Page Styles */
:root {
    --primary-color: #4f46e5;
    --visa-color: #1a1f71;
    --mastercard-color: #000000;
    --amex-color: #006fcf;
    --border-color: #e2e8f0;
    --warning-color: #f59e0b;
    --success-color: #10b981;
    --danger-color: #ef4444;
    --info-color: #3b82f6;
}
.main-content { background-color: #f8fafc; }

/* CSS-ONLY FLIP MECHANISM */
.flipper-checkbox { display: none; }
.card-container { perspective: 1000px; height: 220px; margin-bottom: 1rem; }
.card-inner { position: relative; width: 100%; height: 100%; transition: transform 0.8s; transform-style: preserve-3d; }
.flipper-checkbox:checked ~ .card-container .card-inner { transform: rotateY(180deg); }

.card-front, .card-back {
    position: absolute; width: 100%; height: 100%;
    -webkit-backface-visibility: hidden; backface-visibility: hidden;
    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;
}
.card-front.visa { background: linear-gradient(135deg, #1a1f71, #5b65d9); }
.card-front.mastercard { background: linear-gradient(135deg, #000000, #4a4a4a); }
.card-front.amex { background: linear-gradient(135deg, #006fcf, #65a9e0); }
.card-back { background-color: #d1d5db; transform: rotateY(180deg); color: #1f2937; }

.card-chip { width: 40px; height: 30px; background: linear-gradient(135deg, #ffd700, #ffaa00); border-radius: 4px; }
.card-logo { 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); }
.card-details { font-size: 0.9rem; text-transform: uppercase; }
.card-status { padding: 0.25rem 0.75rem; border-radius: 999px; font-size: 0.75rem; font-weight: 600; background-color: rgba(0,0,0,0.2); }
.card-status.active { background-color: rgba(16, 185, 129, 0.7); }
.card-status.frozen { background-color: rgba(239, 68, 68, 0.7); }

.card-back .magnetic-stripe { height: 40px; background-color: #1f2937; margin: 1rem -1.5rem; }
.card-back .signature-panel { text-align: right; margin-top: 1rem; }
.card-back .signature-panel .cvv-box { background-color: white; color: #1f2937; padding: 0.5rem; border-radius: 4px; display: inline-block; font-family: 'Courier New', monospace; font-weight: bold; }

.card-actions {
    background-color: white; border: 1px solid var(--border-color);
    border-radius: 1rem; padding: 1rem;
    display: flex; gap: 0.5rem; justify-content: space-around;
}
.card-action-btn {
    flex: 1; text-align: center; padding: 0.5rem;
    border-radius: 0.5rem; transition: background-color 0.2s ease;
    cursor: pointer; border: none; background: none;
}
.card-action-btn:hover { background-color: #f8fafc; }

/* External Card Styles */
.external-card-front {
    background: linear-gradient(135deg, #64748b, #94a3b8);
    position: relative;
    overflow: hidden;
}
.external-card-front::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="none" stroke="%23ffffff" stroke-width="2" stroke-dasharray="5,5" opacity="0.2"/></svg>');
    opacity: 0.1;
}
.external-card-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: rgba(255,255,255,0.2);
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

/* Link Card Section */
.link-card-section {
    background-color: white;
    border: 2px dashed var(--border-color);
    border-radius: 1rem;
    padding: 2rem;
    text-align: center;
    transition: all 0.3s ease;
}
.link-card-section:hover {
    border-color: var(--primary-color);
    background-color: var(--primary-light);
}
.link-card-icon {
    font-size: 3rem;
    color: var(--primary-color);
    margin-bottom: 1rem;
}

/* Modal styles */
.modal-content {
    border-radius: 1rem;
    border: none;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
.modal-header {
    border-bottom: 1px solid var(--border-color);
    background-color: var(--primary-light);
    border-radius: 1rem 1rem 0 0;
}
.modal-footer {
    border-top: 1px solid var(--border-color);
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">My Cards</h1>
            <div>
                <button type="button" class="btn btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#linkCardModal">
                    <i class='bx bx-link me-1'></i> Link External Card
                </button>
                <a href="add-card.php" class="btn btn-primary">
                    <i class='bx bx-plus me-1'></i> Add New Card
                </a>
            </div>
        </div>

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

        <!-- Your Cards Section -->
        <h5 class="mb-3">Your Cards</h5>
        <div class="row">
            <?php if (empty($cards)): ?>
                <div class="col-12">
                    <div class="card text-center py-5">
                        <div class="card-body">
                            <i class='bx bx-credit-card-alt' style="font-size: 4rem; color: #cbd5e1;"></i>
                            <h5 class="mt-3">No Cards Found</h5>
                            <p class="text-muted">You have not added any cards to your account yet.</p>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($cards as $index => $card): ?>
                    <div class="col-lg-6 mb-4">
                        <input type="checkbox" class="flipper-checkbox" id="flipper-<?php echo $index; ?>">
                        <div class="card-container">
                            <div class="card-inner">
                                <!-- Card Front & Back -->
                                <div class="card-front <?php echo htmlspecialchars($card['card_type']); ?>">
                                    <div class="card-status <?php echo htmlspecialchars($card['status']); ?>"><?php echo ucfirst($card['status']); ?></div>
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="card-chip"></div>
                                        <div class="card-logo">
                                            <?php if ($card['card_type'] == 'visa'): ?><i class='bx bxl-visa'></i>
                                            <?php elseif ($card['card_type'] == 'mastercard'): ?><i class='bx bxl-mastercard'></i>
                                            <?php else: ?><i class='bx bxl-american-express'></i><?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="card-number"><?php echo formatCardNumber($card['card_number']); ?></div>
                                    <div class="d-flex justify-content-between card-details">
                                        <div><small>Card Holder</small><div><?php echo htmlspecialchars($card['card_holder_name']); ?></div></div>
                                        <div><small>Expires</small><div><?php echo sprintf('%02d', $card['expiry_month']) . '/' . substr($card['expiry_year'], -2); ?></div></div>
                                    </div>
                                </div>
                                <div class="card-back">
                                    <div class="magnetic-stripe"></div>
                                    <div class="signature-panel">
                                        <small>CVV</small>
                                        <div class="cvv-box"><?php echo htmlspecialchars($card['cvv']); ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-actions">
                            <label for="flipper-<?php echo $index; ?>" class="btn card-action-btn text-primary"><i class='bx bx-refresh d-block fs-4 mb-1'></i> Flip Card</label>
                            <form method="POST" action="cards.php" class="d-inline-block flex-fill">
                                <input type="hidden" name="card_id" value="<?php echo $card['id']; ?>">
                                <?php if ($card['status'] == 'active'): ?>
                                    <button type="submit" name="toggle_freeze" value="1" class="btn card-action-btn text-warning w-100"><i class='bx bx-lock d-block fs-4 mb-1'></i> Freeze</button>
                                <?php else: ?>
                                    <button type="submit" name="toggle_freeze" value="1" class="btn card-action-btn text-success w-100"><i class='bx bx-lock-open d-block fs-4 mb-1'></i> Unfreeze</button>
                                <?php endif; ?>
                            </form>
                            <a href="card-details.php?id=<?php echo $card['id']; ?>" class="btn card-action-btn text-info">
                                <i class='bx bx-slider-alt d-block fs-4 mb-1'></i> Details
                            </a>
                            <form method="POST" action="cards.php" class="d-inline-block flex-fill" onsubmit="return confirm('Are you sure you want to permanently remove this card?');">
                                <input type="hidden" name="card_id" value="<?php echo $card['id']; ?>">
                                <button type="submit" name="delete_card" value="1" class="btn card-action-btn text-danger w-100"><i class='bx bx-trash d-block fs-4 mb-1'></i> Remove</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- External Cards Section -->
        <?php if (!empty($external_cards)): ?>
            <h5 class="mb-3 mt-4">Linked External Cards</h5>
            <div class="row">
                <?php foreach ($external_cards as $index => $ext_card): ?>
                    <div class="col-lg-6 mb-4">
                        <div class="card-container">
                            <div class="card-inner">
                                <!-- External Card Front -->
                                <div class="card-front external-card-front <?php echo htmlspecialchars($ext_card['card_type']); ?>">
                                    <div class="external-card-badge">External</div>
                                    <div class="card-status <?php echo htmlspecialchars($ext_card['status']); ?>"><?php echo ucfirst($ext_card['status']); ?></div>
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="card-logo">
                                            <?php if ($ext_card['card_type'] == 'visa'): ?><i class='bx bxl-visa'></i>
                                            <?php elseif ($ext_card['card_type'] == 'mastercard'): ?><i class='bx bxl-mastercard'></i>
                                            <?php else: ?><i class='bx bxl-american-express'></i><?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="card-number"><?php echo $ext_card['card_number']; ?></div>
                                    <div class="d-flex justify-content-between card-details">
                                        <div><small>Card Holder</small><div><?php echo htmlspecialchars($ext_card['card_holder_name']); ?></div></div>
                                        <div><small>Expires</small><div><?php echo sprintf('%02d', $ext_card['expiry_month']) . '/' . substr($ext_card['expiry_year'], -2); ?></div></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-actions">
                            <form method="POST" action="cards.php" class="d-inline-block flex-fill" onsubmit="return confirm('Are you sure you want to unlink this external card?');">
                                <input type="hidden" name="ext_card_id" value="<?php echo $ext_card['id']; ?>">
                                <button type="submit" name="unlink_card" value="1" class="btn card-action-btn text-danger w-100"><i class='bx bx-unlink d-block fs-4 mb-1'></i> Unlink Card</button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Link External Card Modal -->
<div class="modal fade" id="linkCardModal" tabindex="-1" aria-labelledby="linkCardModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="linkCardModalLabel">Link External Card</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="cards.php">
                <div class="modal-body">
                    <div class="mb-3">
                        <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 class="mb-3">
                        <label for="card_number" class="form-label">Card Number</label>
                        <input type="text" class="form-control" id="card_number" name="card_number" required maxlength="19" placeholder="XXXX XXXX XXXX XXXX">
                    </div>
                    <div class="mb-3">
                        <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" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expiry_month" class="form-label">Expiry Month</label>
                            <select class="form-select" id="expiry_month" name="expiry_month" required>
                                <?php for ($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo sprintf('%02d', $i); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expiry_year" class="form-label">Expiry Year</label>
                            <select class="form-select" id="expiry_year" name="expiry_year" required>
                                <?php for ($i = date('Y'); $i <= date('Y') + 10; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="cvv" class="form-label">CVV</label>
                        <input type="password" class="form-control" id="cvv" name="cvv" required maxlength="4" placeholder="XXX">
                    </div>
                    <div class="alert alert-info">
                        <i class='bx bx-shield-quarter me-2'></i>
                        Your card details are encrypted and stored securely. We comply with PCI DSS standards.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="link_external_card" class="btn btn-primary">Link Card</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// Format card number input with spaces
document.getElementById('card_number')?.addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    let formattedValue = '';
    
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    e.target.value = formattedValue;
});
</script>
