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

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

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

// Get card ID from URL and validate it
$card_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$card_id) {
    header("Location: cards.php");
    exit();
}

// --- HANDLE SETTINGS UPDATE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_card_settings'])) {
    $daily_limit = filter_input(INPUT_POST, 'daily_spending_limit', FILTER_VALIDATE_FLOAT);
    $monthly_limit = filter_input(INPUT_POST, 'monthly_spending_limit', FILTER_VALIDATE_FLOAT);
    $online_payments = isset($_POST['online_payments_enabled']) ? 1 : 0;

    if ($daily_limit === false || $monthly_limit === false) {
        $error_message = "Invalid limit amount. Please enter a valid number.";
    } else {
        try {
            $stmt = $db->prepare("UPDATE cards SET daily_spending_limit = ?, monthly_spending_limit = ?, online_payments_enabled = ? WHERE id = ? AND user_id = ?");
            $stmt->execute([$daily_limit, $monthly_limit, $online_payments, $card_id, $_SESSION['user_id']]);
            $success_message = "Card settings have been updated successfully.";
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating settings.";
            error_log("Card Settings Update Error: " . $e->getMessage());
        }
    }
}

// Security Check: Fetch the card details ONLY if it belongs to the logged-in user
$stmt = $db->prepare("SELECT * FROM cards WHERE id = ? AND user_id = ?");
$stmt->execute([$card_id, $_SESSION['user_id']]);
$card = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$card) {
    $_SESSION['error_message'] = "Card not found or permission denied.";
    header("Location: cards.php");
    exit();
}

// Fetch recent transactions
$trans_stmt = $db->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$trans_stmt->execute([$_SESSION['user_id']]);
$transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Placeholder for spending data
$daily_spent = 750.50;
$monthly_spent = 2140.75;
$daily_percentage = ($card['daily_spending_limit'] > 0) ? ($daily_spent / $card['daily_spending_limit']) * 100 : 0;
$monthly_percentage = ($card['monthly_spending_limit'] > 0) ? ($monthly_spent / $card['monthly_spending_limit']) * 100 : 0;


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

<style>
/* Redesigned Card Details Page Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --visa-color: #1a1f71;
    --mastercard-color: #000000;
    --amex-color: #006fcf;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
}
.main-content { background-color: #f8fafc; }

/* Card Visual Styles */
.credit-card-display { perspective: 1000px; }
.credit-card-inner {
    width: 100%; max-width: 400px; margin: auto;
    transition: transform 0.8s; transform-style: preserve-3d;
    /* *** THIS IS THE FIX: Changed from 63% to 56.25% for a wider aspect ratio *** */
    padding-bottom: 56.25%; 
}
.credit-card-display.is-flipped .credit-card-inner { transform: rotateY(180deg); }
.credit-card-front, .credit-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 20px 30px rgba(0,0,0,0.15);
    display: flex; flex-direction: column; justify-content: space-between;
}
.credit-card-front.visa { background: linear-gradient(135deg, #1a1f71, #5b65d9); }
.credit-card-front.mastercard { background: linear-gradient(135deg, #000000, #4a4a4a); }
.credit-card-front.amex { background: linear-gradient(135deg, #006fcf, #65a9e0); }
.credit-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; }
.card-details { font-size: 0.9rem; text-transform: uppercase; }
.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 .cvv-box { background-color: white; color: #1f2937; padding: 0.5rem; border-radius: 4px; display: inline-block; font-family: 'Courier New', monospace; font-weight: bold; }

/* Stat Cards */
.stat-card {
    background-color: white;
    border: 1px solid var(--border-color);
    border-radius: 1rem;
    padding: 1.5rem;
    text-align: center;
}
.stat-card-icon { font-size: 2rem; margin-bottom: 0.5rem; }
.stat-card-label { font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem; }
.stat-card-value { font-size: 1.25rem; font-weight: 600; }
.progress-bar-container { height: 8px; background-color: #e2e8f0; border-radius: 999px; overflow: hidden; margin-top: 0.5rem; }
.progress-bar-fill { height: 100%; background-color: var(--primary-color); border-radius: 999px; }

/* Tab Styles */
.nav-pills .nav-link { border-radius: 0.75rem; font-weight: 500; }
.nav-pills .nav-link.active { background-color: var(--primary-color); }
.form-check-input:checked { background-color: var(--primary-color); border-color: var(--primary-color); }
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex align-items-center mb-4">
            <a href="cards.php" class="btn btn-light me-3" style="border-radius: 50%; width: 40px; height: 40px; display: grid; place-content: center;"><i class='bx bx-arrow-back'></i></a>
            <div>
                <h1 class="h3 mb-0">Card Details</h1>
                <p class="text-muted mb-0">Manage your <?php echo ucfirst($card['card_type']); ?> card ending in <?php echo substr($card['card_number'], -4); ?></p>
            </div>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Card Display -->
        <div class="credit-card-display mb-5" id="cardDisplay">
            <div class="credit-card-inner">
                <div class="credit-card-front <?php echo htmlspecialchars($card['card_type']); ?>">
                    <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="credit-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>

        <!-- Stats Row -->
        <div class="row mb-5">
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon" style="color: <?php echo $card['status'] == 'active' ? 'var(--success-color)' : 'var(--warning-color)'; ?>;"><i class='bx bx-check-shield'></i></div>
                    <div class="stat-card-label">Card Status</div>
                    <div class="stat-card-value"><?php echo ucfirst($card['status']); ?></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon text-primary"><i class='bx bx-sun'></i></div>
                    <div class="stat-card-label">Daily Spending Limit</div>
                    <div class="stat-card-value"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($daily_spent, 2); ?> / <?php echo number_format($card['daily_spending_limit'], 2); ?></div>
                    <div class="progress-bar-container"><div class="progress-bar-fill" style="width: <?php echo $daily_percentage; ?>%;"></div></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon text-primary"><i class='bx bx-calendar'></i></div>
                    <div class="stat-card-label">Monthly Spending Limit</div>
                    <div class="stat-card-value"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($monthly_spent, 2); ?> / <?php echo number_format($card['monthly_spending_limit'], 2); ?></div>
                    <div class="progress-bar-container"><div class="progress-bar-fill" style="width: <?php echo $monthly_percentage; ?>%;"></div></div>
                </div>
            </div>
        </div>

        <!-- Tabs for Settings and Transactions -->
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-pills card-header-pills" id="pills-tab" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" id="pills-settings-tab" data-bs-toggle="pill" data-bs-target="#pills-settings" type="button">Settings</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="pills-transactions-tab" data-bs-toggle="pill" data-bs-target="#pills-transactions" type="button">Transactions</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="pills-statements-tab" data-bs-toggle="pill" data-bs-target="#pills-statements" type="button">Statements</button></li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="pills-tabContent">
                    <div class="tab-pane fade show active" id="pills-settings" role="tabpanel">
                        <h5 class="mb-4">Card Controls & Limits</h5>
                        <form method="POST" action="card-details.php?id=<?php echo $card_id; ?>">
                            <ul class="list-group mb-4">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-0">Online Payments</h6>
                                        <small class="text-muted">Allow or block payments on websites.</small>
                                    </div>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="online_payments_enabled" role="switch" <?php echo ($card['online_payments_enabled']) ? 'checked' : ''; ?>>
                                    </div>
                                </li>
                            </ul>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="daily_spending_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" name="daily_spending_limit" value="<?php echo htmlspecialchars($card['daily_spending_limit']); ?>" step="100">
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="monthly_spending_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" name="monthly_spending_limit" value="<?php echo htmlspecialchars($card['monthly_spending_limit']); ?>" step="500">
                                    </div>
                                </div>
                            </div>
                            <div class="text-end mt-3">
                                <button type="submit" name="update_card_settings" class="btn btn-primary">Save Settings</button>
                            </div>
                        </form>
                    </div>
                    <div class="tab-pane fade" id="pills-transactions" role="tabpanel">
                        <h5 class="mb-4">Recent Transactions on this Card</h5>
                        <?php if (empty($transactions)): ?>
                            <p class="text-muted text-center">No transactions to display.</p>
                        <?php else: ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach ($transactions as $tx): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="fw-bold"><?php echo htmlspecialchars($tx['description']); ?></div>
                                            <small class="text-muted"><?php echo date('M d, Y', strtotime($tx['created_at'])); ?></small>
                                        </div>
                                        <div class="fw-bold text-<?php echo $tx['type'] == 'credit' ? 'success' : 'danger'; ?>">
                                            <?php echo $tx['type'] == 'credit' ? '+' : '-'; ?><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($tx['amount'], 2); ?>
                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                    <div class="tab-pane fade" id="pills-statements" role="tabpanel">
                        <h5 class="mb-4">Monthly Statements</h5>
                        <p class="text-muted text-center">This feature is coming soon.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
// Simple script to make the card flippable on click
document.getElementById('cardDisplay').addEventListener('click', function() {
    this.classList.toggle('is-flipped');
});
</script>
