<?php 
$this->load->view('layouts/header');
$this->load->helper('layout');
?>

    <!-- App Header -->
    <div class="appHeader">
        <div class="left">
            <a href="<?php echo base_url('cards'); ?>" class="headerButton">
                <ion-icon name="chevron-back-outline"></ion-icon>
            </a>
        </div>
        <div class="pageTitle">Card Details</div>
        <div class="right">
            <a href="#" class="headerButton" data-bs-toggle="dropdown">
                <ion-icon name="ellipsis-vertical-outline"></ion-icon>
            </a>
            <div class="dropdown-menu dropdown-menu-end">
                <?php if ($card->status == 'active'): ?>
                <a class="dropdown-item" href="#" onclick="freezeCard()">
                    <ion-icon name="snow-outline"></ion-icon> Freeze Card
                </a>
                <?php else: ?>
                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#unfreezeModal">
                    <ion-icon name="sunny-outline"></ion-icon> Unfreeze Card
                </a>
                <?php endif; ?>
                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#limitsModal">
                    <ion-icon name="options-outline"></ion-icon> Set Limits
                </a>
            </div>
        </div>
    </div>

    <!-- App Capsule -->
    <div id="appCapsule">
        
        <?php if ($this->session->flashdata('success')): ?>
        <div class="section mt-2">
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $this->session->flashdata('success'); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
        <?php endif; ?>

        <!-- Card Display -->
        <div class="section mt-2">
            <div class="card-block bg-<?php echo $card->status == 'active' ? 'primary' : ($card->status == 'frozen' ? 'secondary' : 'dark'); ?>">
                <div class="card-main">
                    <div class="card-button">
                        <?php if ($card->status != 'active'): ?>
                        <span class="badge bg-danger">
                            <ion-icon name="snow-outline"></ion-icon> <?php echo ucfirst($card->status); ?>
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="balance">
                        <span class="label">BALANCE</span>
                        <h1 class="title"><?php echo format_money($card->balance, $card->currency); ?></h1>
                    </div>
                    <div class="in">
                        <div class="card-number">
                            <span class="label">Card Number</span>
                            <span id="cardNumber" class="masked"><?php echo $card->card_number_masked; ?></span>
                            <a href="#" onclick="toggleCardNumber()" class="ms-2">
                                <ion-icon name="eye-outline" id="eyeIcon"></ion-icon>
                            </a>
                        </div>
                        <div class="bottom">
                            <div class="card-expiry">
                                <span class="label">Expiry</span>
                                <?php echo $card->expiry_month; ?> / <?php echo substr($card->expiry_year, -2); ?>
                            </div>
                            <div class="card-ccv">
                                <span class="label">CVV</span>
                                <span id="cardCvv">***</span>
                                <a href="#" onclick="toggleCvv()" class="ms-1">
                                    <ion-icon name="eye-outline" id="cvvEyeIcon"></ion-icon>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="section mt-3">
            <div class="row">
                <div class="col-4 text-center mb-2">
                    <a href="<?php echo base_url('cards/fund/' . $card->id); ?>" class="text-decoration-none">
                        <div class="rounded-circle bg-success d-flex align-items-center justify-content-center mb-1" style="width: 56px; height: 56px; margin: 0 auto;">
                            <ion-icon name="add-outline" style="font-size: 26px; color: #fff;"></ion-icon>
                        </div>
                        <span class="small text-success">Fund Card</span>
                    </a>
                </div>
                <div class="col-4 text-center mb-2">
                    <a href="<?php echo base_url('cards/withdraw/' . $card->id); ?>" class="text-decoration-none">
                        <div class="rounded-circle bg-warning d-flex align-items-center justify-content-center mb-1" style="width: 56px; height: 56px; margin: 0 auto;">
                            <ion-icon name="remove-outline" style="font-size: 26px; color: #fff;"></ion-icon>
                        </div>
                        <span class="small text-warning">Withdraw</span>
                    </a>
                </div>
                <div class="col-4 text-center mb-2">
                    <a href="<?php echo base_url('cards/transactions/' . $card->id); ?>" class="text-decoration-none">
                        <div class="rounded-circle bg-info d-flex align-items-center justify-content-center mb-1" style="width: 56px; height: 56px; margin: 0 auto;">
                            <ion-icon name="list-outline" style="font-size: 26px; color: #fff;"></ion-icon>
                        </div>
                        <span class="small text-info">History</span>
                    </a>
                </div>
            </div>
        </div>

        <!-- Card Controls -->
        <div class="section mt-3">
            <div class="section-title">Card Controls</div>
            <div class="card">
                <ul class="listview flush transparent image-listview">
                    <li>
                        <div class="item">
                            <div class="icon-box bg-primary">
                                <ion-icon name="globe-outline"></ion-icon>
                            </div>
                            <div class="in">
                                <div>Online Transactions</div>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="onlineEnabled" 
                                           <?php echo $card->is_online_enabled ? 'checked' : ''; ?>
                                           onchange="updateControls()">
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item">
                            <div class="icon-box bg-success">
                                <ion-icon name="card-outline"></ion-icon>
                            </div>
                            <div class="in">
                                <div>POS Transactions</div>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="posEnabled"
                                           <?php echo $card->is_pos_enabled ? 'checked' : ''; ?>
                                           onchange="updateControls()">
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item">
                            <div class="icon-box bg-warning">
                                <ion-icon name="cash-outline"></ion-icon>
                            </div>
                            <div class="in">
                                <div>ATM Withdrawals</div>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="atmEnabled"
                                           <?php echo $card->is_atm_enabled ? 'checked' : ''; ?>
                                           onchange="updateControls()">
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item">
                            <div class="icon-box bg-danger">
                                <ion-icon name="airplane-outline"></ion-icon>
                            </div>
                            <div class="in">
                                <div>International Transactions</div>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="internationalEnabled"
                                           <?php echo $card->is_international_enabled ? 'checked' : ''; ?>
                                           onchange="updateControls()">
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Card Info -->
        <div class="section mt-3">
            <div class="section-title">Card Information</div>
            <div class="card">
                <ul class="listview flush transparent simple-listview">
                    <li class="p-2">
                        <strong>Card Type</strong>
                        <span><?php echo ucfirst($card->card_type); ?></span>
                    </li>
                    <li class="p-2">
                        <strong>Card Brand</strong>
                        <span><?php echo ucfirst($card->card_brand); ?></span>
                    </li>
                    <li class="p-2">
                        <strong>Currency</strong>
                        <span><?php echo $card->currency; ?></span>
                    </li>
                    <li class="p-2">
                        <strong>Daily Limit</strong>
                        <span><?php echo format_money($card->daily_limit, $card->currency); ?></span>
                    </li>
                    <li class="p-2">
                        <strong>Monthly Limit</strong>
                        <span><?php echo format_money($card->monthly_limit, $card->currency); ?></span>
                    </li>
                    <li class="p-2">
                        <strong>Created</strong>
                        <span><?php echo date('M d, Y', strtotime($card->created_at)); ?></span>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="section mt-3 mb-3">
            <div class="section-heading">
                <h2 class="title">Recent Transactions</h2>
                <a href="<?php echo base_url('cards/transactions/' . $card->id); ?>" class="link">View All</a>
            </div>
            
            <?php if (empty($transactions)): ?>
            <div class="card">
                <div class="card-body text-center py-4">
                    <ion-icon name="receipt-outline" style="font-size: 48px; color: #ccc;"></ion-icon>
                    <p class="text-muted mt-2 mb-0">No transactions yet</p>
                </div>
            </div>
            <?php else: ?>
            <div class="transactions">
                <?php foreach (array_slice($transactions, 0, 5) as $txn): ?>
                <div class="item">
                    <div class="detail">
                        <div class="icon-box bg-<?php echo $txn->type == 'credit' ? 'success' : 'danger'; ?>">
                            <ion-icon name="<?php echo $txn->type == 'credit' ? 'arrow-down' : 'arrow-up'; ?>-outline"></ion-icon>
                        </div>
                        <div>
                            <strong><?php echo htmlspecialchars($txn->merchant ?? $txn->description); ?></strong>
                            <p><?php echo date('M d, Y H:i', strtotime($txn->created_at)); ?></p>
                        </div>
                    </div>
                    <div class="right">
                        <div class="price text-<?php echo $txn->type == 'credit' ? 'success' : 'danger'; ?>">
                            <?php echo $txn->type == 'credit' ? '+' : '-'; ?>
                            <?php echo format_money($txn->amount, $card->currency); ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Unfreeze Modal -->
    <div class="modal fade action-sheet" id="unfreezeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Unfreeze Card</h5>
                </div>
                <div class="modal-body">
                    <div class="action-sheet-content">
                        <form id="unfreezeForm">
                            <?php if ($user->user_type !== 'admin'): ?>
                            <p>Enter your transaction PIN to unfreeze this card.</p>
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Transaction PIN</label>
                                    <input type="password" class="form-control" name="pin" maxlength="4" placeholder="Enter PIN" required>
                                </div>
                            </div>
                            <?php else: ?>
                            <p>Click below to unfreeze this card.</p>
                            <?php endif; ?>
                            <div class="form-group basic mt-3">
                                <button type="submit" class="btn btn-primary btn-block btn-lg">Unfreeze Card</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Limits Modal -->
    <div class="modal fade action-sheet" id="limitsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Card Limits</h5>
                </div>
                <div class="modal-body">
                    <div class="action-sheet-content">
                        <form id="limitsForm">
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Daily Limit (<?php echo $card->currency; ?>)</label>
                                    <input type="number" class="form-control" name="daily_limit" value="<?php echo $card->daily_limit; ?>">
                                </div>
                            </div>
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Monthly Limit (<?php echo $card->currency; ?>)</label>
                                    <input type="number" class="form-control" name="monthly_limit" value="<?php echo $card->monthly_limit; ?>">
                                </div>
                            </div>
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Single Transaction Limit (<?php echo $card->currency; ?>)</label>
                                    <input type="number" class="form-control" name="single_transaction_limit" value="<?php echo $card->single_transaction_limit; ?>">
                                </div>
                            </div>
                            <div class="form-group basic mt-3">
                                <button type="submit" class="btn btn-primary btn-block btn-lg">Update Limits</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- App Bottom Menu -->
    <?php echo get_bottom_menu('cards'); ?>

    <script>
    var cardId = <?php echo $card->id; ?>;
    var showiUSDumber = false;
    var showingCvv = false;
    
    function toggleCardNumber() {
        var el = document.getElementById('cardNumber');
        var icon = document.getElementById('eyeIcon');
        if (showiUSDumber) {
            el.textContent = '<?php echo $card->card_number_masked; ?>';
            icon.name = 'eye-outline';
            showiUSDumber = false;
        } else {
            // In a real app, this would fetch the full number from server with PIN verification
            MeridianDialog.info('Full card number display requires PIN verification');
        }
    }
    
    function toggleCvv() {
        var el = document.getElementById('cardCvv');
        var icon = document.getElementById('cvvEyeIcon');
        if (showingCvv) {
            el.textContent = '***';
            icon.name = 'eye-outline';
            showingCvv = false;
        } else {
            MeridianDialog.info('CVV display requires PIN verification');
        }
    }
    
    function freezeCard() {
        MeridianDialog.confirm('Are you sure you want to freeze this card?', function() {
            fetch(base_url + 'cards/freeze/' + cardId, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'csrf_token=' + csrf_token
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    MeridianDialog.success(data.message);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    MeridianDialog.error(data.message);
                }
            });
        });
    }
    
    document.getElementById('unfreezeForm').addEventListener('submit', function(e) {
        e.preventDefault();
        var pin = this.pin.value;
        
        fetch(base_url + 'cards/unfreeze/' + cardId, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'csrf_token=' + csrf_token + '&pin=' + pin
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                MeridianDialog.success(data.message);
                setTimeout(() => location.reload(), 1500);
            } else {
                MeridianDialog.error(data.message);
            }
        });
    });
    
    document.getElementById('limitsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('csrf_token', csrf_token);
        
        fetch(base_url + 'cards/limits/' + cardId, {
            method: 'POST',
            body: new URLSearchParams(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                MeridianDialog.success(data.message);
                bootstrap.Modal.getInstance(document.getElementById('limitsModal')).hide();
                setTimeout(() => location.reload(), 1500);
            } else {
                MeridianDialog.error(data.message);
            }
        });
    });
    
    function updateControls() {
        var data = {
            csrf_token: csrf_token,
            is_online_enabled: document.getElementById('onlineEnabled').checked ? 1 : 0,
            is_pos_enabled: document.getElementById('posEnabled').checked ? 1 : 0,
            is_atm_enabled: document.getElementById('atmEnabled').checked ? 1 : 0,
            is_international_enabled: document.getElementById('internationalEnabled').checked ? 1 : 0
        };
        
        fetch(base_url + 'cards/controls/' + cardId, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams(data)
        })
        .then(response => response.json())
        .then(data => {
            // Silently update or show toast
        });
    }
    </script>

<?php $this->load->view('layouts/footer'); ?>
