<?php
// Standardized admin page setup
require_once __DIR__ . '/config.php';
require_admin_login();

// Search param
$search = trim($_GET['search'] ?? '');

// Handle POST actions
if (is_post()) {
    verify_csrf();
    
    // Add service
    if (isset($_POST['add_service'])) {
        $name = trim($_POST['name'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $sort_order = (int)($_POST['sort_order'] ?? 0);

        if ($name === '') {
            set_flash("Service name cannot be empty.", "danger");
        } else {
            $stmt = $pdo->prepare("INSERT INTO services (name, price, sort_order) VALUES (?, ?, ?)");
            $stmt->execute([$name, $price, $sort_order]);
            set_flash("Service added successfully.", "success");
            redirect('services.php');
        }
    }

    // Update sort order (Quick Update)
    if (isset($_POST['update_order'])) {
        $sid = (int)$_POST['sid'];
        $new_order = (int)$_POST['new_order'];
        $stmt = $pdo->prepare("UPDATE services SET sort_order = ? WHERE id = ?");
        $stmt->execute([$new_order, $sid]);
        set_flash("Order updated.", "success");
        redirect('services.php');
    }

    // Delete service
    if (isset($_POST['delete_service'])) {
        $sid = (int)($_POST['sid'] ?? 0);
        if ($sid) {
            $stmt = $pdo->prepare("DELETE FROM services WHERE id=?");
            $stmt->execute([$sid]);
            set_flash("Service deleted successfully.", "success");
            redirect('services.php');
        }
    }
}

// Fetch services (with search and sort_order)
$params = [];
$sql = "SELECT * FROM services";
if ($search !== '') {
    $sql .= " WHERE name LIKE ?";
    $params[] = "%$search%";
}
$sql .= " ORDER BY sort_order ASC, id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$services_all = $stmt->fetchAll();

// Pagination Logic
function paginate($items, $perPage=12) {
    $total = count($items);
    $pages = max(1, ceil($total / $perPage));
    $current = max(1, (int)($_GET['page'] ?? 1));
    $start = ($current - 1) * $perPage;
    return [array_slice($items, $start, $perPage), $pages, $current];
}

list($services, $pages, $current) = paginate($services_all, 12);

function render_pagination($pages, $current, $search='') {
    if ($pages < 2) return '';
    $html = '<nav><ul class="pagination justify-content-center">';
    for ($i=1;$i<=$pages;$i++) {
        $active = $i==$current ? 'active' : '';
        $q = ($search !== '') ? '&search='.urlencode($search) : '';
        $html .= "<li class='page-item $active'><a class='page-link' href='?page=$i$q'>$i</a></li>";
    }
    $html .= '</ul></nav>';
    return $html;
}

require_once 'header.php';
?>

<style>
    :root {
        --brand-color: #230133;
        --brand-hover: #3b0354;
    }
    
    .bg-brand { background-color: var(--brand-color) !important; color: white; }
    .text-brand { color: var(--brand-color) !important; }
    .btn-brand { background-color: var(--brand-color); color: white; border: none; }
    .btn-brand:hover { background-color: var(--brand-hover); color: white; }
    
    .card-header-brand {
        background-color: var(--brand-color) !important;
        color: white !important;
    }
    
    .table thead th {
        background-color: #f8f9fc;
        color: var(--brand-color);
        font-weight: 700;
        border-bottom: 2px solid var(--brand-color);
    }
    
    .page-item.active .page-link {
        background-color: var(--brand-color);
        border-color: var(--brand-color);
    }
    
    .page-link { color: var(--brand-color); }

    .form-control:focus {
        border-color: var(--brand-color);
        box-shadow: 0 0 0 0.25rem rgba(35, 1, 51, 0.25);
    }
</style>

<div class="container-fluid py-4">
    <div class="d-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-brand fw-bold">Services Management</h1>
    </div>

    <?php show_flash(); ?>

    <div class="card shadow-sm mb-4">
        <div class="card-header card-header-brand py-3">
            <h6 class="m-0 fw-bold"><i class="bi bi-plus-circle-fill me-2"></i>Add New Service</h6>
        </div>
        <div class="card-body">
            <form method="post" class="row g-3 align-items-center">
                <?php csrf_field(); ?>
                <div class="col-md-5">
                    <label class="small fw-bold text-muted">Service Name</label>
                    <input type="text" name="name" class="form-control" placeholder="e.g. Free Fire Diamond" required>
                </div>
                <div class="col-md-3">
                    <label class="small fw-bold text-muted">Base Price</label>
                    <div class="input-group">
                        <span class="input-group-text bg-light">৳</span>
                        <input type="number" step="0.01" name="price" class="form-control" placeholder="0.00" required>
                    </div>
                </div>
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Serial Order</label>
                    <input type="number" name="sort_order" class="form-control" placeholder="1, 2, 3..." value="0">
                </div>
                <div class="col-md-2">
                    <label class="invisible d-block small">Submit</label>
                    <button type="submit" class="btn btn-brand w-100 fw-bold" name="add_service">Add Service</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-header py-3 d-flex flex-wrap justify-content-between align-items-center bg-white border-bottom">
            <h6 class="m-0 fw-bold text-brand"><i class="bi bi-tags-fill me-2"></i>Existing Services</h6>
            <form method="get" class="d-flex mt-2 mt-md-0" style="max-width: 300px;">
                <input type="text" name="search" class="form-control form-control-sm me-2" placeholder="Search service..." value="<?php echo h($search); ?>">
                <button class="btn btn-sm btn-brand" type="submit">Search</button>
            </form>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th width="180">Serial / Order</th>
                            <th>Service Name</th>
                            <th>Base Price</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($services)): ?>
                            <tr><td colspan="4" class="text-center text-muted p-4">No services found.</td></tr>
                        <?php else: foreach($services as $s): ?>
                            <tr>
                                <td>
                                    <form method="post" class="d-flex gap-1">
                                        <?php csrf_field(); ?>
                                        <input type="hidden" name="sid" value="<?php echo $s['id']; ?>">
                                        <input type="number" name="new_order" class="form-control form-control-sm border-brand" value="<?php echo $s['sort_order']; ?>" style="width: 70px;">
                                        <button type="submit" name="update_order" class="btn btn-sm btn-brand px-2">Save</button>
                                    </form>
                                </td>
                                <td>
                                    <div class="fw-bold text-dark"><?php echo h($s['name']); ?></div>
                                    <small class="text-muted">ID: #<?php echo $s['id']; ?></small>
                                </td>
                                <td class="fw-bold text-brand">৳ <?php echo number_format($s['price'], 2); ?></td>
                                <td class="text-center">
                                    <form method="post" class="d-inline">
                                        <?php csrf_field(); ?>
                                        <input type="hidden" name="sid" value="<?php echo $s['id']; ?>">
                                        <button type="submit" name="delete_service" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this service?')">
                                            <i class="bi bi-trash-fill"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="mt-4">
                <?php echo render_pagination($pages, $current, $search); ?>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>