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

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

$error_message = '';

// --- HANDLE ADD NEW CARD FORM SUBMISSION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_card'])) {
    $card_number = preg_replace('/\D/', '', $_POST['card_number'] ?? '');
    $card_holder_name = trim($_POST['card_holder_name'] ?? '');
    $expiry_month = intval($_POST['expiry_month'] ?? 0);
    $expiry_year = intval($_POST['expiry_year'] ?? 0);
    $cvv = trim($_POST['cvv'] ?? '');
    $card_type = strtolower(trim($_POST['card_type'] ?? ''));
    
    $errors = [];
    if (strlen($card_number) < 13 || strlen($card_number) > 19) { $errors[] = "Card number must be between 13 and 19 digits."; }
    if (empty($card_holder_name)) { $errors[] = "Card holder name is required."; }
    if ($expiry_month < 1 || $expiry_month > 12) { $errors[] = "Invalid expiry month."; }
    if ($expiry_year < date('Y') || $expiry_year > date('Y') + 20) { $errors[] = "Invalid expiry year."; }
    if (strlen($cvv) < 3 || strlen($cvv) > 4 || !is_numeric($cvv)) { $errors[] = "CVV must be 3 or 4 digits."; }
    if (!in_array($card_type, ['visa', 'mastercard', 'amex'])) { $errors[] = "Invalid card type."; }
    
    $stmt = $db->prepare("SELECT id FROM cards WHERE user_id = ? AND card_number = ?");
    $stmt->execute([$_SESSION['user_id'], $card_number]);
    if ($stmt->rowCount() > 0) { $errors[] = "This card is already registered to your account."; }
    
    if (empty($errors)) {
        try {
            $stmt = $db->prepare("INSERT INTO cards (user_id, card_number, card_holder_name, expiry_month, expiry_year, cvv, card_type, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'active')");
            $stmt->execute([$_SESSION['user_id'], $card_number, $card_holder_name, $expiry_month, $expiry_year, $cvv, $card_type]);
            
            // Set success message in session and redirect
            $_SESSION['success_message'] = "Your new card has been added successfully.";
            header("Location: cards.php");
            exit();
        } catch (PDOException $e) {
            $error_message = "An error occurred while adding your card. Please try again.";
            error_log("Add Card Error: " . $e->getMessage());
        }
    } else {
        $error_message = implode("<br>", $errors);
    }
}

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

<style>
/* Add Card Page Styles */
:root {
    --primary-color: #4f46e5;
    --visa-color: #1a1f71;
    --mastercard-color: #000000;
    --amex-color: #006fcf;
}
.main-content { background-color: #f8fafc; }
.card-preview {
    width: 100%;
    height: 220px;
    border-radius: 1rem;
    padding: 1.5rem;
    color: white;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    margin-bottom: 1.5rem;
    position: relative;
    overflow: hidden;
    transition: background 0.3s ease;
    display: flex; flex-direction: column; justify-content: space-between;
}
.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; }
.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; }
</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">Add a New Card</h1>
            <a href="cards.php" class="btn btn-secondary">Back to My Cards</a>
        </div>

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

        <div class="row">
            <div class="col-lg-7">
                <div class="card">
                    <div class="card-body p-4">
                        <form method="POST" action="add-card.php" id="addCardForm">
                            <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" placeholder="1234 5678 9012 3456" required maxlength="19">
                            </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" placeholder="John Doe" 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="text" class="form-control" id="cvv" name="cvv" placeholder="123" required maxlength="4" pattern="\d{3,4}">
                                <div class="form-text">3 or 4 digits on the back of your card</div>
                            </div>
                            <div class="d-grid">
                                <button type="submit" name="add_card" class="btn btn-primary btn-lg">Add Card</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-lg-5">
                <div class="card-preview visa" id="cardPreview">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="card-chip"></div>
                        <div class="card-logo"><i class='bx bxl-visa' id="cardLogo"></i></div>
                    </div>
                    <div class="card-number" id="previewCardNumber">•••• •••• •••• ••••</div>
                    <div class="d-flex justify-content-between card-details">
                        <div><small>Card Holder</small><div id="previewCardHolder">YOUR NAME</div></div>
                        <div><small>Expires</small><div id="previewExpiry">MM/YY</div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Card Preview Functionality
    const cardTypeSelect = document.getElementById('card_type');
    const cardNumberInput = document.getElementById('card_number');
    const cardHolderInput = document.getElementById('card_holder_name');
    const expiryMonthSelect = document.getElementById('expiry_month');
    const expiryYearSelect = document.getElementById('expiry_year');
    
    const cardPreview = document.getElementById('cardPreview');
    const cardLogo = document.getElementById('cardLogo');
    const previewCardNumber = document.getElementById('previewCardNumber');
    const previewCardHolder = document.getElementById('previewCardHolder');
    const previewExpiry = document.getElementById('previewExpiry');
    
    cardTypeSelect.addEventListener('change', function() {
        cardPreview.className = 'card-preview ' + this.value;
        if (this.value === 'visa') { cardLogo.className = 'bx bxl-visa'; } 
        else if (this.value === 'mastercard') { cardLogo.className = 'bx bxl-mastercard'; } 
        else if (this.value === 'amex') { cardLogo.className = 'bx bxl-american-express'; }
    });
    
    cardNumberInput.addEventListener('input', function(e) {
        let value = this.value.replace(/\D/g, '');
        let formattedValue = '';
        for (let i = 0; i < value.length; i++) {
            if (i > 0 && i % 4 === 0) { formattedValue += ' '; }
            formattedValue += value[i];
        }
        this.value = formattedValue;
        previewCardNumber.textContent = formattedValue || '•••• •••• •••• ••••';
    });
    
    cardHolderInput.addEventListener('input', function() {
        previewCardHolder.textContent = this.value.trim().toUpperCase() || 'YOUR NAME';
    });
    
    function updateExpiry() {
        const month = expiryMonthSelect.value.padStart(2, '0');
        const year = expiryYearSelect.value.slice(-2);
        previewExpiry.textContent = `${month}/${year}`;
    }
    
    expiryMonthSelect.addEventListener('change', updateExpiry);
    expiryYearSelect.addEventListener('change', updateExpiry);
    updateExpiry();
});
</script>
