<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';
$u_name = $_SESSION['user_name'] ?? 'User';
$swal_script = "";

$site_query = $conn->query("SELECT site_name FROM settings WHERE id = 1");
$site_data = $site_query->fetch_assoc();
$display_name = $site_data['site_name'] ?? 'ApiNexus';

// Capture Search Input
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, trim($_GET['search'])) : '';
$search_param = !empty($search) ? "&search=" . urlencode($search) : "";

if (isset($_GET['action']) && isset($_GET['id'])) {
    $target_id = mysqli_real_escape_string($conn, $_GET['id']);
    $new_status = ($_GET['action'] == 'activate') ? 'Active' : 'Inactive';
    
    $update = $conn->query("UPDATE users SET status = '$new_status' WHERE id = '$target_id'");
    
    if ($update) {
        $page_return = isset($_GET['page']) ? $_GET['page'] : 1;
        $swal_script = "Swal.fire({
            title: 'Success!',
            text: 'User status updated to $new_status.',
            icon: 'success',
            confirmButtonColor: '#2c7be5'
        }).then(() => { window.location.href='user_list.php?page=$page_return$search_param'; });";
    }
}

if (isset($_GET['login_as']) && $utype == 'TitanAdmin') {
    $login_id = mysqli_real_escape_string($conn, $_GET['login_as']);
    $user_data = $conn->query("SELECT * FROM users WHERE id = '$login_id'")->fetch_assoc();
    if ($user_data) {
        $_SESSION['user_id'] = $user_data['id'];
        $_SESSION['utype'] = $user_data['user_type']; 
        $_SESSION['user_type'] = $user_data['user_type'];
        $_SESSION['user_name'] = $user_data['name'];
        
        $swal_script = "Swal.fire({
            title: 'Switching Account',
            text: 'Redirecting to User Dashboard...',
            icon: 'info',
            timer: 1500,
            showConfirmButton: false
        }).then(() => { window.location.href='titanhome.php'; });";
    }
}

// ---------------- SEARCH & PAGINATION LOGIC START ----------------
$limit = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Base Condition based on Role
if ($utype == 'TitanAdmin') {
    $base_filter = "1=1"; // Admin sees everyone
} else {
    $base_filter = "referred_by = '$uid'"; // Others see their referrals
}

// Append Search Filter if exists
if (!empty($search)) {
    $base_filter .= " AND (name LIKE '%$search%' OR phone LIKE '%$search%' OR email LIKE '%$search%')";
}

// Count total matching records
$count_query = "SELECT COUNT(id) AS total FROM users WHERE $base_filter";
$count_result = $conn->query($count_query);
$count_row = $count_result->fetch_assoc();
$total_records = $count_row['total'];
$total_pages = ceil($total_records / $limit);

// Main Table Data Query
$query = "SELECT * FROM users WHERE $base_filter ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = $conn->query($query);
// ---------------- SEARCH & PAGINATION LOGIC END ----------------
?>

<div class="row mb-3">
    <div class="col">
        <div class="card shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <img class="ms-n2" src="../assets/img/illustrations/crm-bar-chart.png" alt="" width="90" />
                    <div>
                        <h6 class="text-primary fs-10 mb-0">Welcome back, <?php echo htmlspecialchars($u_name); ?></h6>
                        <h4 class="text-primary fw-bold mb-0"><?php echo htmlspecialchars($display_name); ?> <span class="text-info fw-medium">Users</span></h4>
                    </div>
                </div>
                <div class="col-md-auto">
                    <div class="form-control form-control-sm border-200">
                        <span class="fas fa-calendar-day text-primary me-2"></span>
                        <span class="fw-bold text-primary"><?php echo date('d M, Y'); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3">
    <div class="card-header border-bottom">
        <div class="row align-items-center flex-between-center gap-2">
            <div class="col-sm-auto">
                <h5 class="mb-0 text-primary fw-bold"><span class="fas fa-users me-2"></span>Manage Accounts</h5>
            </div>
            
            <div class="col-sm-auto d-flex flex-wrap gap-2 align-items-center">
                <form method="GET" class="m-0">
                    <div class="input-group input-group-sm">
                        <input type="text" name="search" class="form-control shadow-none border-200" placeholder="Search name, phone, email..." value="<?php echo htmlspecialchars($search); ?>" style="min-width: 250px;">
                        <button class="btn btn-primary px-3 shadow-none" type="submit"><i class="fas fa-search"></i></button>
                        <?php if(!empty($search)): ?>
                            <a href="user_list.php" class="btn btn-secondary shadow-none px-2 text-nowrap"><i class="fas fa-times me-1"></i>Clear</a>
                        <?php endif; ?>
                    </div>
                </form>
                
                <a class="btn btn-primary btn-sm shadow-none text-nowrap" href="add_user.php"><span class="fas fa-plus me-1"></span> New User</a>
            </div>
        </div>
    </div>
    
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped fs-10 mb-0">
                <thead>
                    <tr>
                        <th class="align-middle ps-3">User Details</th>
                        <th class="align-middle">Contact Info</th>
                        <th class="align-middle">Role</th>
                        <th class="align-middle">Balance</th>
                        <th class="align-middle text-center">Status</th>
                        <th class="align-middle text-end pe-3">Action</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td class="align-middle ps-3">
                            <div class="fw-bold text-body-emphasis"><?php echo htmlspecialchars($row['name']); ?></div>
                            <div class="fs-11 text-body-secondary"><?php echo htmlspecialchars($row['shop_name']); ?></div>
                        </td>
                        <td class="align-middle">
                            <div class="fw-semi-bold text-primary"><i class="fas fa-phone-alt me-1 fs-11 text-500"></i><?php echo htmlspecialchars($row['phone']); ?></div>
                            <div class="fs-11 text-body-secondary"><i class="fas fa-envelope me-1 text-500"></i><?php echo htmlspecialchars($row['email']); ?></div>
                        </td>
                        <td class="align-middle">
                            <?php 
                                $u_role = $row['user_type'];
                                $badge_class = 'badge-subtle-primary';
                                if($u_role == 'TitanAdmin') $badge_class = 'badge-subtle-danger';
                                if($u_role == 'Head Branch') $badge_class = 'badge-subtle-warning';
                                if($u_role == 'Distributor') $badge_class = 'badge-subtle-info';
                            ?>
                            <span class="badge <?php echo $badge_class; ?>"><?php echo $u_role; ?></span>
                        </td>
                        <td class="align-middle fw-bold text-success">
                            ₹<?php echo number_format($row['wallet'], 2); ?>
                        </td>
                        <td class="align-middle text-center">
                            <?php if($row['status'] == 'Active'): ?>
                                <span class="badge rounded-pill badge-subtle-success"><span class="fas fa-check me-1"></span>Active</span>
                            <?php else: ?>
                                <span class="badge rounded-pill badge-subtle-danger"><span class="fas fa-times me-1"></span>Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td class="align-middle text-end pe-3">
                            <div class="btn-group">
                                <?php if($row['status'] == 'Active'): ?>
                                    <a class="btn btn-link text-danger p-0 ms-3" href="user_list.php?action=deactivate&id=<?php echo $row['id']; ?>&page=<?php echo $page; ?><?php echo $search_param; ?>" title="Deactivate"><span class="fas fa-user-slash"></span></a>
                                <?php else: ?>
                                    <a class="btn btn-link text-success p-0 ms-3" href="user_list.php?action=activate&id=<?php echo $row['id']; ?>&page=<?php echo $page; ?><?php echo $search_param; ?>" title="Activate"><span class="fas fa-user-check"></span></a>
                                <?php endif; ?>

                                <?php if($utype == 'TitanAdmin' && $row['id'] != $uid): ?>
                                    <a class="btn btn-link text-info p-0 ms-3" href="user_list.php?login_as=<?php echo $row['id']; ?>" title="Secret Login"><span class="fas fa-user-secret"></span></a>
                                <?php endif; ?>
                                
                                <a class="btn btn-link text-warning p-0 ms-3" href="edit_user.php?id=<?php echo $row['id']; ?>" title="Edit Info"><span class="fas fa-user-edit"></span></a>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    <?php else: ?>
                    <tr><td colspan="6" class="text-center py-4 text-body-secondary fst-italic">No matching members found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php if($total_pages > 1): ?>
    <div class="card-footer d-flex justify-content-end border-top bg-100 py-2">
        <ul class="pagination pagination-sm mb-0">
            <li class="page-item <?php if($page <= 1) { echo 'disabled'; } ?>">
                <a class="page-link shadow-none" href="<?php if($page <= 1) { echo '#'; } else { echo "?page=".($page - 1).$search_param; } ?>">&laquo; Prev</a>
            </li>

            <?php 
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $page + 2);
                
                if($start_page > 1) echo '<li class="page-item disabled"><a class="page-link shadow-none" href="#">...</a></li>';
                
                for($i = $start_page; $i <= $end_page; $i++): 
            ?>
                <li class="page-item <?php if($page == $i) { echo 'active'; } ?>">
                    <a class="page-link shadow-none" href="?page=<?php echo $i; ?><?php echo $search_param; ?>"><?php echo $i; ?></a>
                </li>
            <?php endfor; ?>
            
            <?php if($end_page < $total_pages) echo '<li class="page-item disabled"><a class="page-link shadow-none" href="#">...</a></li>'; ?>

            <li class="page-item <?php if($page >= $total_pages) { echo 'disabled'; } ?>">
                <a class="page-link shadow-none" href="<?php if($page >= $total_pages) { echo '#'; } else { echo "?page=".($page + 1).$search_param; } ?>">Next &raquo;</a>
            </li>
        </ul>
    </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    <?php echo $swal_script; ?>
</script>

<?php require_once('../titancore/TitanFooter.php'); ?>