<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

// Handle price update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_price'])) {
        $item_type = $_POST['item_type'];
        $price = floatval($_POST['price']);
        $old_price = !empty($_POST['old_price']) ? floatval($_POST['old_price']) : null;
        $discount = !empty($_POST['discount']) ? intval($_POST['discount']) : 0;
        
        $conn->query("UPDATE payment_items SET price = '$price', old_price = '$old_price', discount_percent = '$discount', updated_at = NOW() WHERE item_type = '$item_type'");
        $success = "Price updated successfully!";
    }
    
    if (isset($_POST['toggle_status'])) {
        $item_type = $_POST['item_type'];
        $conn->query("UPDATE payment_items SET is_active = NOT is_active WHERE item_type = '$item_type'");
        $success = "Status updated!";
    }
    
    if (isset($_POST['add_item'])) {
        $item_type = strtolower(str_replace(' ', '_', $_POST['item_name']));
        $conn->query("
            INSERT INTO payment_items (item_type, item_name, description, price, display_order) 
            VALUES ('$item_type', '{$_POST['item_name']}', '{$_POST['description']}', '{$_POST['price']}', '{$_POST['display_order']}')
        ");
        $success = "Item added successfully!";
    }
    
    if (isset($_POST['delete_item'])) {
        $item_type = $_POST['item_type'];
        $conn->query("DELETE FROM payment_items WHERE item_type = '$item_type'");
        $success = "Item deleted!";
    }
}

// Get all payment items
$items = $conn->query("SELECT * FROM payment_items ORDER BY display_order ASC");

$page_title = 'Payment Settings | Admin';
include '../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Settings - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        .price-card { background: white; border-radius: 16px; padding: 20px; margin-bottom: 15px; transition: 0.2s; border-left: 4px solid #d4a017; }
        .price-card:hover { transform: translateX(5px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        .price-label { font-weight: 700; color: #0a3d2f; font-size: 1rem; }
        .price-value { font-size: 1.3rem; font-weight: 800; color: #d4a017; }
        .old-price { text-decoration: line-through; color: #999; font-size: 0.85rem; margin-left: 10px; }
        .discount-badge { background: #28a745; color: white; padding: 2px 8px; border-radius: 20px; font-size: 0.7rem; margin-left: 10px; }
        .status-badge { padding: 3px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; }
        .status-active { background: #28a745; color: white; }
        .status-inactive { background: #dc3545; color: white; }
        .btn-edit { background: #d4a017; color: #0a3d2f; border: none; border-radius: 30px; padding: 5px 15px; font-size: 0.8rem; }
        .btn-edit:hover { background: #b8860b; color: white; }
    </style>
</head>
<body>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="fas fa-tags me-2" style="color: #d4a017;"></i> Payment Settings</h2>
            <p class="text-muted">Set and manage prices for all products and services</p>
        </div>
        <div>
            <button class="btn btn-primary rounded-pill" data-bs-toggle="modal" data-bs-target="#addItemModal">
                <i class="fas fa-plus me-2"></i> Add New Item
            </button>
            <a href="dashboard.php" class="btn btn-outline-secondary rounded-pill ms-2">
                <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <!-- Price List -->
    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-header bg-white border-0 pt-3">
            <h5><i class="fas fa-list me-2"></i> Product & Service Prices</h5>
        </div>
        <div class="card-body">
            <?php if($items && $items->num_rows > 0): ?>
                <?php while($item = $items->fetch_assoc()): ?>
                    <div class="price-card">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <div class="price-label"><?= htmlspecialchars($item['item_name']) ?></div>
                                <small class="text-muted"><?= htmlspecialchars($item['description']) ?></small>
                            </div>
                            <div class="col-md-3">
                                <span class="price-value">₦<?= number_format($item['price'], 2) ?></span>
                                <?php if($item['old_price']): ?>
                                    <span class="old-price">₦<?= number_format($item['old_price'], 2) ?></span>
                                <?php endif; ?>
                                <?php if($item['discount_percent'] > 0): ?>
                                    <span class="discount-badge">-<?= $item['discount_percent'] ?>%</span>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-2">
                                <span class="status-badge <?= $item['is_active'] ? 'status-active' : 'status-inactive' ?>">
                                    <?= $item['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </div>
                            <div class="col-md-3 text-end">
                                <button class="btn-edit btn-sm me-1" onclick="editPrice('<?= $item['item_type'] ?>', '<?= htmlspecialchars($item['item_name']) ?>', <?= $item['price'] ?>, <?= $item['old_price'] ?: 'null' ?>, <?= $item['discount_percent'] ?>)">
                                    <i class="fas fa-edit me-1"></i> Edit Price
                                </button>
                                <button class="btn btn-sm btn-outline-secondary me-1" onclick="toggleStatus('<?= $item['item_type'] ?>')">
                                    <i class="fas fa-<?= $item['is_active'] ? 'ban' : 'play' ?>"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteItem('<?= $item['item_type'] ?>')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="text-muted text-center py-4">No payment items configured yet. Click "Add New Item" to get started.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Edit Price Modal -->
<div class="modal fade" id="editPriceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-edit me-2"></i> Edit Price</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="item_type" id="edit_item_type">
                    <div class="mb-3">
                        <label class="form-label">Item Name</label>
                        <input type="text" id="edit_item_name" class="form-control" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Current Price (₦)</label>
                        <input type="number" name="price" id="edit_price" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Old Price (₦) - Optional</label>
                        <input type="number" name="old_price" id="edit_old_price" class="form-control" placeholder="For showing discount">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Discount Percentage (%)</label>
                        <input type="number" name="discount" id="edit_discount" class="form-control" placeholder="e.g., 20">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_price" class="btn btn-primary">Update Price</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Item Modal -->
<div class="modal fade" id="addItemModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i> Add New Payment Item</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Item Name</label>
                        <input type="text" name="item_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Price (₦)</label>
                        <input type="number" name="price" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Display Order</label>
                        <input type="number" name="display_order" class="form-control" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_item" class="btn btn-success">Add Item</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editPrice(itemType, itemName, price, oldPrice, discount) {
    document.getElementById('edit_item_type').value = itemType;
    document.getElementById('edit_item_name').value = itemName;
    document.getElementById('edit_price').value = price;
    document.getElementById('edit_old_price').value = oldPrice !== 'null' ? oldPrice : '';
    document.getElementById('edit_discount').value = discount || 0;
    new bootstrap.Modal(document.getElementById('editPriceModal')).show();
}

function toggleStatus(itemType) {
    if(confirm('Change status for this item?')) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="item_type" value="' + itemType + '"><input type="hidden" name="toggle_status" value="1">';
        document.body.appendChild(form);
        form.submit();
    }
}

function deleteItem(itemType) {
    if(confirm('Delete this item permanently? This action cannot be undone.')) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="item_type" value="' + itemType + '"><input type="hidden" name="delete_item" value="1">';
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

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