<?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') {
    $card_id = $_POST['card_id'] ?? null;
    $user_id = $_SESSION['user_id'] ?? null;

    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.";
                }
            }
        }
    }
}

// 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);

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

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; }
</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>
            <a href="add-card.php" class="btn btn-primary">
                <i class='bx bx-plus me-1'></i> Add New Card
            </a>
        </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; ?>

        <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>
                            <!-- *** THE CORRECTED DETAILS/SETTINGS LINK *** -->
                            <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>
    </div>
</div>

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