<?php
session_start();
include 'db.php';
include 'layout.php';

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $card_code = strtoupper(trim($_POST['card_code']));
                $card_name = trim($_POST['card_name']);
                $display_name = trim($_POST['display_name']);
                $icon_class = trim($_POST['icon_class']);
                $color_class = trim($_POST['color_class']);
                $default_charge_rate = (float)$_POST['default_charge_rate'];
                $sort_order = (int)$_POST['sort_order'];
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                // Check if card code already exists
                $check = $conn->prepare("SELECT id FROM card_types WHERE card_code = ?");
                $check->bind_param("s", $card_code);
                $check->execute();
                $check->store_result();
                
                if ($check->num_rows > 0) {
                    $error = "Card code already exists.";
                } else {
                    $stmt = $conn->prepare("INSERT INTO card_types (card_code, card_name, display_name, icon_class, color_class, default_charge_rate, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("sssssdii", $card_code, $card_name, $display_name, $icon_class, $color_class, $default_charge_rate, $sort_order, $is_active);
                    
                    if ($stmt->execute()) {
                        $message = "Card type added successfully!";
                    } else {
                        $error = "Failed to add card type.";
                    }
                    $stmt->close();
                }
                $check->close();
                break;

            case 'update':
                $id = (int)$_POST['id'];
                $card_code = strtoupper(trim($_POST['card_code']));
                $card_name = trim($_POST['card_name']);
                $display_name = trim($_POST['display_name']);
                $icon_class = trim($_POST['icon_class']);
                $color_class = trim($_POST['color_class']);
                $default_charge_rate = (float)$_POST['default_charge_rate'];
                $sort_order = (int)$_POST['sort_order'];
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                // Check if card code already exists (excluding current record)
                $check = $conn->prepare("SELECT id FROM card_types WHERE card_code = ? AND id != ?");
                $check->bind_param("si", $card_code, $id);
                $check->execute();
                $check->store_result();
                
                if ($check->num_rows > 0) {
                    $error = "Card code already exists.";
                } else {
                    $stmt = $conn->prepare("UPDATE card_types SET card_code = ?, card_name = ?, display_name = ?, icon_class = ?, color_class = ?, default_charge_rate = ?, sort_order = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("sssssdiis", $card_code, $card_name, $display_name, $icon_class, $color_class, $default_charge_rate, $sort_order, $is_active, $id);
                    
                    if ($stmt->execute()) {
                        $message = "Card type updated successfully!";
                    } else {
                        $error = "Failed to update card type.";
                    }
                    $stmt->close();
                }
                $check->close();
                break;

            case 'delete':
                $id = (int)$_POST['id'];
                
                // Check if card type is in use
                $usage_check = $conn->query("SELECT COUNT(*) as count FROM account_transactions WHERE card_type_id = $id");
                $usage = $usage_check->fetch_assoc();
                
                if ($usage['count'] > 0) {
                    $error = "Cannot delete card type. It is being used in " . $usage['count'] . " transactions.";
                } else {
                    $stmt = $conn->prepare("DELETE FROM card_types WHERE id = ?");
                    $stmt->bind_param("i", $id);
                    
                    if ($stmt->execute()) {
                        $message = "Card type deleted successfully!";
                    } else {
                        $error = "Failed to delete card type.";
                    }
                    $stmt->close();
                }
                break;
        }
    }
}

// Get all card types
$card_types = $conn->query("SELECT * FROM card_types ORDER BY sort_order, card_name");
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Card Types Management</h4>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <!-- Add New Card Type Button -->
        <div class="mb-3">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus"></i> Add New Card Type
            </button>
        </div>

        <!-- Card Types List -->
        <div class="card">
            <div class="card-header">
                <h5>Card Types List</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Code</th>
                                <th>Name</th>
                                <th>Display Name</th>
                                <th>Icon</th>
                                <th>Charge Rate</th>
                                <th>Sort Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($card_type = $card_types->fetch_assoc()): ?>
                                <tr>
                                    <td><?= $card_type['id'] ?></td>
                                    <td><strong><?= htmlspecialchars($card_type['card_code']) ?></strong></td>
                                    <td><?= htmlspecialchars($card_type['card_name']) ?></td>
                                    <td><?= htmlspecialchars($card_type['display_name']) ?></td>
                                    <td>
                                        <?php if ($card_type['icon_class']): ?>
                                            <i class="<?= htmlspecialchars($card_type['icon_class']) ?>"></i>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= number_format($card_type['default_charge_rate'], 2) ?>%</td>
                                    <td><?= $card_type['sort_order'] ?></td>
                                    <td>
                                        <span class="badge <?= $card_type['is_active'] ? 'bg-success' : 'bg-secondary' ?>">
                                            <?= $card_type['is_active'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="editCardType(<?= htmlspecialchars(json_encode($card_type)) ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this card type?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $card_type['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Card Type</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="add_card_code" class="form-label">Card Code <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="add_card_code" name="card_code" required placeholder="VISA">
                        </div>
                        <div class="col-md-6">
                            <label for="add_card_name" class="form-label">Card Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="add_card_name" name="card_name" required placeholder="VISA">
                        </div>
                        <div class="col-md-6">
                            <label for="add_display_name" class="form-label">Display Name</label>
                            <input type="text" class="form-control" id="add_display_name" name="display_name" placeholder="VISA Card">
                        </div>
                        <div class="col-md-6">
                            <label for="add_icon_class" class="form-label">Icon</label>
                            <select class="form-select" id="add_icon_class" name="icon_class">
                                <option value="fas fa-credit-card">Credit Card</option>
                                <option value="fab fa-cc-visa">VISA</option>
                                <option value="fab fa-cc-mastercard">MasterCard</option>
                                <option value="fab fa-cc-amex">American Express</option>
                                <option value="fab fa-cc-discover">Discover</option>
                                <option value="fas fa-qrcode">QR Code</option>
                                <option value="fas fa-mobile-alt">Mobile Payment</option>
                                <option value="fab fa-paypal">PayPal</option>
                                <option value="fas fa-wallet">Wallet</option>
                                <option value="fas fa-university">Bank</option>
                                <option value="fas fa-money-bill-wave">Cash</option>
                                <option value="fas fa-coins">Coins</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="add_color_class" class="form-label">Color</label>
                            <select class="form-select" id="add_color_class" name="color_class">
                                <option value="btn-outline-primary">Primary (Blue)</option>
                                <option value="btn-outline-success">Success (Green)</option>
                                <option value="btn-outline-warning">Warning (Yellow)</option>
                                <option value="btn-outline-danger">Danger (Red)</option>
                                <option value="btn-outline-info">Info (Cyan)</option>
                                <option value="btn-outline-secondary">Secondary (Gray)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="add_default_charge_rate" class="form-label">Default Charge Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="add_default_charge_rate" name="default_charge_rate" value="0.00">
                        </div>
                        <div class="col-md-6">
                            <label for="add_sort_order" class="form-label">Sort Order</label>
                            <input type="number" class="form-control" id="add_sort_order" name="sort_order" value="0">
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="add_is_active" name="is_active" checked>
                                <label class="form-check-label" for="add_is_active">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Card Type</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="editForm">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Card Type</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="edit_card_code" class="form-label">Card Code <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_card_code" name="card_code" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_card_name" class="form-label">Card Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="edit_card_name" name="card_name" required>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_display_name" class="form-label">Display Name</label>
                            <input type="text" class="form-control" id="edit_display_name" name="display_name">
                        </div>
                        <div class="col-md-6">
                            <label for="edit_icon_class" class="form-label">Icon</label>
                            <select class="form-select" id="edit_icon_class" name="icon_class">
                                <option value="fas fa-credit-card">Credit Card</option>
                                <option value="fab fa-cc-visa">VISA</option>
                                <option value="fab fa-cc-mastercard">MasterCard</option>
                                <option value="fab fa-cc-amex">American Express</option>
                                <option value="fab fa-cc-discover">Discover</option>
                                <option value="fas fa-qrcode">QR Code</option>
                                <option value="fas fa-mobile-alt">Mobile Payment</option>
                                <option value="fab fa-paypal">PayPal</option>
                                <option value="fas fa-wallet">Wallet</option>
                                <option value="fas fa-university">Bank</option>
                                <option value="fas fa-money-bill-wave">Cash</option>
                                <option value="fas fa-coins">Coins</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_color_class" class="form-label">Color</label>
                            <select class="form-select" id="edit_color_class" name="color_class">
                                <option value="btn-outline-primary">Primary (Blue)</option>
                                <option value="btn-outline-success">Success (Green)</option>
                                <option value="btn-outline-warning">Warning (Yellow)</option>
                                <option value="btn-outline-danger">Danger (Red)</option>
                                <option value="btn-outline-info">Info (Cyan)</option>
                                <option value="btn-outline-secondary">Secondary (Gray)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="edit_default_charge_rate" class="form-label">Default Charge Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="edit_default_charge_rate" name="default_charge_rate">
                        </div>
                        <div class="col-md-6">
                            <label for="edit_sort_order" class="form-label">Sort Order</label>
                            <input type="number" class="form-control" id="edit_sort_order" name="sort_order">
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active">
                                <label class="form-check-label" for="edit_is_active">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Card Type</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editCardType(cardType) {
    document.getElementById('edit_id').value = cardType.id;
    document.getElementById('edit_card_code').value = cardType.card_code;
    document.getElementById('edit_card_name').value = cardType.card_name;
    document.getElementById('edit_display_name').value = cardType.display_name || '';
    document.getElementById('edit_icon_class').value = cardType.icon_class || '';
    document.getElementById('edit_color_class').value = cardType.color_class || 'btn-outline-primary';
    document.getElementById('edit_default_charge_rate').value = cardType.default_charge_rate || 0;
    document.getElementById('edit_sort_order').value = cardType.sort_order || 0;
    document.getElementById('edit_is_active').checked = cardType.is_active == 1;
    
    new bootstrap.Modal(document.getElementById('editModal')).show();
}
</script>

