<?php
session_start();
include 'includes/header.php'; include 'includes/sidebar.php'; include 'includes/connect.php';

if(!isset($_SESSION['distributor_id'])){
    header("Location: login.php");
    exit;
}

$role = $_SESSION['role'];
$distributor_id = $_SESSION['distributor_id'];

$search = isset($_GET['search']) ? $_GET['search'] : '';
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;

if($role == 'Super-Admin'){

    // 🔥 SUPER ADMIN - ALL DATA
   $query = "SELECT d.*, p.name as parent_name
              FROM distributor d
              LEFT JOIN distributor p ON d.parent_id = p.id
              WHERE (d.name LIKE '%$search%' OR d.email LIKE '%$search%')
              ORDER BY d.id DESC
              LIMIT $start, $limit";

    $total_query = "SELECT COUNT(*) as total 
                    FROM distributor 
                    WHERE (name LIKE '%$search%' OR email LIKE '%$search%')";

} else {

    // 🔒 DISTRIBUTOR - ONLY THEIR NURSERY
    $query = "SELECT d.*, p.name as parent_name
              FROM distributor d
              LEFT JOIN distributor p ON d.parent_id = p.id
              WHERE d.role = 'nursery'
              AND d.parent_id = '$distributor_id'
              AND (d.name LIKE '%$search%' OR d.email LIKE '%$search%')
              ORDER BY d.id DESC
              LIMIT $start, $limit";

    $total_query = "SELECT COUNT(*) as total 
                    FROM distributor 
                    WHERE role = 'nursery'
                    AND parent_id = '$distributor_id'
                    AND (name LIKE '%$search%' OR email LIKE '%$search%')";
}

$result = mysqli_query($conn, $query);
$total_result = mysqli_query($conn, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);
?>

<style>
.badge {
    display: inline-block;
    padding: 6px 12px;
    font-size: 12px;
    border-radius: 20px;
    font-weight: 500;
    color: #fff;
}

.badge-success { background: #28a745; }
.badge-primary { background: #007bff; }
.badge-danger { background: #dc3545; }

.badge-light {
    background: #f1f3f5;
    color: #333;
    border: 1px solid #ddd;
}

/* Alignment fix (UNCHANGED) */
.table-title,
.wg-product.item-row {
    display: flex;
    align-items: center;
}

.table-title li {
    flex: 1;
}

.wg-product.item-row > div,
.wg-product.item-row .list-icon-function {
    flex: 1;
}

.wg-product.item-row .list-icon-function {
    flex: 0.8;
}

.table-title li:nth-child(1),
.wg-product.item-row > div:nth-child(1) { flex: 1.5; }

.table-title li:nth-child(2),
.wg-product.item-row > div:nth-child(2) { flex: 2; }

.table-title li:nth-child(3),
.wg-product.item-row > div:nth-child(3) { flex: 1.2; }

.table-title li:nth-child(4),
.wg-product.item-row > div:nth-child(4) { flex: 1; }

.table-title li:nth-child(5),
.wg-product.item-row > div:nth-child(5) { flex: 1.5; }

.table-title li:nth-child(6),
.wg-product.item-row > div:nth-child(6) { flex: 1; }

.table-title li:nth-child(7),
.wg-product.item-row .list-icon-function { flex: 0.8; }

.table-title li,
.wg-product.item-row > div {
    padding: 0 10px;
    box-sizing: border-box;
}

.body-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>

<div class="main-content-inner">
<div class="main-content-wrap">

<div class="flex items-center flex-wrap justify-between gap20 mb-30">

    <h3>All Nursery</h3>

    <div style="display:flex; gap:10px; flex-wrap:wrap;">
        <a class="tf-button px-40" href="add_distributor.php">
            <i class="icon-plus"></i> Add New
        </a>

        <a class="tf-button px-40" href="add_sub_distributor.php">
            <i class="icon-plus"></i> Add Sub Nursery
        </a>
    </div>

</div>

<div class="wg-box">

    <div class="wg-table table-all-category mt-20">

        <ul class="table-title flex gap20 mb-14">
            <li><div class="body-title">Name</div></li>
            <li><div class="body-title">Email</div></li>
            <li><div class="body-title">Mobile</div></li>
            <li><div class="body-title">Role</div></li>
            <li><div class="body-title">Parent</div></li>
            <li><div class="body-title">Status</div></li>
            <li><div class="body-title">Action</div></li>
        </ul>

        <ul class="flex flex-column">

            <?php if(mysqli_num_rows($result) > 0){ ?>
                <?php while($row = mysqli_fetch_assoc($result)){ ?>

                <li class="wg-product item-row gap20">

                    <div class="body-text fw-500">
                        <?php echo htmlspecialchars($row['name']); ?>
                    </div>

                    <div class="body-text">
                        <?php echo htmlspecialchars($row['email']); ?>
                    </div>

                    <div class="body-text">
                        <?php echo htmlspecialchars($row['mobile']); ?>
                    </div>

                    <!-- ✅ FIXED ROLE (DYNAMIC) -->
                    <div class="body-text">
                        <?php if($row['role'] == 'Super-Admin'){ ?>
                            <span class="badge badge-danger">Super-Admin</span>
                        <?php } elseif($row['role'] == 'distributor'){ ?>
                            <span class="badge badge-primary">Distributor</span>
                        <?php } elseif($row['role'] == 'nursery'){ ?>
                            <span class="badge badge-success">Nursery</span>
                        <?php } else { ?>
                            <span class="badge badge-light"><?php echo htmlspecialchars($row['role']); ?></span>
                        <?php } ?>
                    </div>

                    <div class="body-text">
                        <?php if($row['parent_name']){ ?>
                            <span class="badge badge-light">
                                <?php echo htmlspecialchars($row['parent_name']); ?>
                            </span>
                        <?php } else { echo "-"; } ?>
                    </div>

                    <div class="body-text">
                        <?php if($row['status'] == 'Active'){ ?>
                            <span class="badge badge-success">Active</span>
                        <?php } else { ?>
                            <span class="badge badge-danger">Inactive</span>
                        <?php } ?>
                    </div>

                    <div class="list-icon-function">

                        <a href="edit_distributor.php?id=<?php echo $row['id']; ?>" class="item edit">
                            <i class="icon-edit-3"></i>
                        </a>

                        <button class="item trash delete-btn" data-id="<?php echo $row['id']; ?>" style="background:none;border:none;">
                            <i class="icon-trash-2"></i>
                        </button>

                    </div>

                </li>

                <?php } ?>
            <?php } else { ?>

                <li>
                    <div class="body-text">No nursery found</div>
                </li>

            <?php } ?>

        </ul>

    </div>

</div>

</div>
</div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('.delete-btn').click(function(){
        var id = $(this).data('id');
        if(confirm('Are you sure you want to delete this nursery?')){
            $.ajax({
                url: 'delete_distributor.php',
                type: 'POST',
                data: {id: id},
                success: function(){
                    location.reload();
                },
                error: function(){
                    alert('Error deleting nursery');
                }
            });
        }
    });
});
</script>