<?php
define('SECURE_ACCESS', true);

$pageTitle = "Our Team";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$search = trim($_GET['search'] ?? '');
$designation_id = isset($_GET['designation']) && $_GET['designation'] !== '' ? (int)$_GET['designation'] : null;

// Fetch unique designations for filter dropdown
$designations_list = [];
try {
    if ($pdo) {
        $stmt_desig = $pdo->query("SELECT id, title FROM designations ORDER BY id DESC");
        $designations_list = $stmt_desig->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (PDOException $e) {}

// Construct where query
$where = ["u.status = 'active'"];
$params = [];

if ($search !== '') {
    $where[] = "(u.username ILIKE :search OR u.employee_code ILIKE :search)";
    $params['search'] = '%' . $search . '%';
}

if ($designation_id !== null) {
    $where[] = "u.designation_id = :designation_id";
    $params['designation_id'] = $designation_id;
}

$where_str = implode(" AND ", $where);

// Pagination config
$limit = 12;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$total_records = 0;
$total_pages = 0;
$team_members = [];

try {
    if ($pdo) {
        $count_query = "SELECT COUNT(*) FROM users u INNER JOIN designations d ON u.designation_id = d.id WHERE $where_str";
        $stmt_count = $pdo->prepare($count_query);
        $stmt_count->execute($params);
        $total_records = (int)$stmt_count->fetchColumn() ?: 0;
        $total_pages = ceil($total_records / $limit);

        $stmt = $pdo->prepare("
            SELECT u.id, u.username, u.first_name, u.last_name, u.email, u.employee_code, u.profile_picture_url, u.created_at, d.title as designation_title, d.id as designation_rank
            FROM users u
            INNER JOIN designations d ON u.designation_id = d.id
            WHERE $where_str
            ORDER BY d.id DESC, u.username ASC
            LIMIT $limit OFFSET $offset
        ");
        $stmt->execute($params);
        $team_members = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (PDOException $e) {}

require_once __DIR__ . '/../includes/header.php';
?>

<!-- Hero Header Section -->
<div class="bg-primary bg-opacity-10 py-5 mb-4 rounded-4 text-center px-3 border border-primary border-opacity-10">
    <div class="max-width-800 mx-auto">
        <span class="badge bg-primary text-uppercase font-monospace mb-2" style="font-size: 0.75rem; letter-spacing: 1px;">Corporate Hierarchy</span>
        <h1 class="display-5 fw-bold text-dark mb-3">Our Corporate Team & Leaders</h1>
        <p class="lead text-secondary mb-0">Meet the high-performing network leaders sorted by corporate designation rank levels.</p>
    </div>
</div>

<!-- Search & Interactivity Filter Card -->
<form method="GET" action="our_team" id="filterForm" class="card border-0 shadow-sm mb-4">
    <div class="card-body p-3 p-md-4">
        <div class="row g-3">
            <div class="col-12 col-md-8">
                <div class="input-group">
                    <span class="input-group-text bg-light text-secondary border-end-0"><i class="bi bi-search"></i></span>
                    <input type="text" name="search" id="leaderSearch" class="form-control bg-light border-start-0 ps-0" placeholder="Search by leader username or employee code..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
            </div>
            <div class="col-12 col-md-4">
                <select name="designation" id="designationFilter" class="form-select bg-light" onchange="this.form.submit();">
                    <option value="">-- All Ranks / Designations --</option>
                    <?php foreach ($designations_list as $desig): ?>
                        <option value="<?php echo htmlspecialchars($desig['id']); ?>" <?php echo $designation_id == $desig['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($desig['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>
</form>

<div class="container-fluid px-0">
    <!-- Section 1: Corporate Team (Valid Designations, Sorted Higher to Lower) -->
    <div class="mb-5">
        <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-2">
            <h3 class="fw-bold text-dark mb-0">
                <i class="bi bi-award-fill text-primary me-2"></i>Our Dedicate Team Members
            </h3>
            <span id="activeCount" class="badge bg-secondary font-monospace small"><?php echo $total_records; ?> matching</span>
        </div>

        <?php if (empty($team_members)): ?>
            <div class="text-center py-5 text-muted bg-light rounded border">
                <i class="bi bi-people fs-2 mb-2 d-block text-secondary"></i>
                <span class="small">No corporate team members registered with valid designations yet.</span>
            </div>
        <?php else: ?>
            <div class="row g-4 justify-content-center" id="leadersGrid">
                <?php foreach ($team_members as $member): ?>
                    <?php
                    // Set rank-specific visual styles
                    $badge_class = 'bg-secondary';
                    $icon_class = 'bi-patch-check-fill text-secondary';
                    $border_color = 'border-secondary';
                    $header_bg = 'bg-secondary bg-opacity-25';
                    
                    if ($member['designation_rank'] >= 5) {
                        $badge_class = 'bg-danger text-white';
                        $icon_class = 'bi-star-fill text-white';
                        $border_color = 'border-danger';
                        $header_bg = 'bg-danger bg-opacity-75';
                    } elseif ($member['designation_rank'] == 4) {
                        $badge_class = 'bg-warning text-dark';
                        $icon_class = 'bi-award-fill text-dark';
                        $border_color = 'border-warning';
                        $header_bg = 'bg-warning bg-opacity-75';
                    } elseif ($member['designation_rank'] == 3) {
                        $badge_class = 'bg-info text-dark';
                        $icon_class = 'bi-trophy-fill text-dark';
                        $border_color = 'border-info';
                        $header_bg = 'bg-info bg-opacity-75';
                    } elseif ($member['designation_rank'] == 2) {
                        $badge_class = 'bg-primary text-white';
                        $icon_class = 'bi-shield-fill text-white';
                        $border_color = 'border-primary';
                        $header_bg = 'bg-primary bg-opacity-75';
                    }

                    $full_name_seed = trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? '')) ?: $member['username'];
                    $avatar_path = !empty($member['profile_picture_url']) && file_exists(__DIR__ . '/' . $member['profile_picture_url']) 
                        ? $member['profile_picture_url'] 
                        : 'https://api.dicebear.com/7.x/initials/svg?seed=' . urlencode($full_name_seed) . '&backgroundColor=f1f5f9&textColor=1e293b';
                    ?>
                    <!-- Individual Leader ID Card -->
                    <div class="col-12 col-md-6 col-lg-4 leader-card-col mb-4" 
                         data-username="<?php echo htmlspecialchars(strtolower($member['username'])); ?>"
                         data-code="<?php echo htmlspecialchars(strtolower($member['employee_code'])); ?>"
                         data-designation="<?php echo htmlspecialchars($member['designation_title']); ?>">
                        <div class="card id-card border-0 shadow-sm rounded-4 overflow-hidden text-center hover-lift transition h-100" onclick="window.location.href='public_profile/<?php echo $member['id']; ?>'" style="cursor: pointer; min-height: 440px; border: 1px solid rgba(0,0,0,0.08) !important;">
                            <!-- ID Card Header Banner with Site Logo -->
                            <div class="<?php echo $header_bg; ?> py-3 px-3 d-flex align-items-center justify-content-center" style="height: 65px; border-bottom: 2px solid rgba(0,0,0,0.05);">
                                <?php if (!empty($site_logo)): ?>
                                    <img src="<?php echo htmlspecialchars($prefix . $site_logo); ?>?v=<?php echo file_exists(__DIR__ . '/' . $site_logo) ? filemtime(__DIR__ . '/' . $site_logo) : time(); ?>" alt="Logo" style="max-height: 28px; max-width: 130px; object-fit: contain; filter: drop-shadow(0px 1px 2px rgba(255,255,255,0.7));">
                                <?php else: ?>
                                    <span class="fw-bold text-dark font-monospace" style="font-size: 0.85rem; letter-spacing: 1px;"><?php echo htmlspecialchars($site_name); ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Profile Picture -->
                            <div class="position-relative pt-3 mb-3 text-center">
                                <div class="d-inline-block position-relative">
                                    <img src="<?php echo htmlspecialchars($avatar_path); ?>" 
                                         alt="Avatar" 
                                         class="rounded-circle bg-white border border-4 border-white shadow animate-avatar" 
                                         style="width: 90px; height: 90px; object-fit: cover; z-index: 2; position: relative;">
                                    <span class="position-absolute bottom-0 end-0 p-1 rounded-circle shadow-sm border border-light d-flex align-items-center justify-content-center <?php echo $badge_class; ?>" style="width: 28px; height: 28px; transform: translate(15%, 15%); z-index: 3;">
                                        <i class="bi <?php echo $icon_class; ?> fs-6"></i>
                                    </span>
                                </div>
                            </div>
                            
                            <!-- Card Body -->
                            <div class="card-body px-4 pt-0 pb-3 d-flex flex-column justify-content-between">
                                <div>
                                    <h4 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars(trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? '')) ?: $member['username']); ?></h4>
                                    
                                    <!-- ID Details Block -->
                                    <div class="bg-light rounded-3 p-3 my-3 text-start">
                                        <div class="d-flex justify-content-between mb-1">
                                            <span class="text-secondary small fw-bold">ROLE</span>
                                            <span class="text-dark small fw-semibold text-truncate ms-2" style="max-width: 160px;"><?php echo htmlspecialchars($member['designation_title']); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between">
                                            <span class="text-secondary small fw-bold">EMAIL</span>
                                            <span class="font-monospace text-dark small text-truncate ms-2" style="max-width: 160px;"><?php echo htmlspecialchars($member['email']); ?></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div>
                                    <!-- Designation label above Bar Code -->
                                    <div class="mb-3">
                                        <span class="badge <?php echo $badge_class; ?> font-monospace text-uppercase" style="font-size: 0.68rem; letter-spacing: 1px; padding: 6px 12px; border-radius: 50px;">
                                            <?php echo htmlspecialchars($member['designation_title']); ?>
                                        </span>
                                    </div>
                                    
                                    <!-- Stylized Simulated Barcode for ID Badge realism -->
                                    <div class="barcode mx-auto mb-2" style="width: 150px; height: 26px; opacity: 0.85; background: repeating-linear-gradient(90deg, #1e293b, #1e293b 2px, transparent 2px, transparent 5px, #1e293b 5px, #1e293b 7px, transparent 7px, transparent 9px, #1e293b 9px, #1e293b 10px, transparent 10px, transparent 12px, #1e293b 12px, #1e293b 15px, transparent 15px, transparent 18px);"></div>
                                    <small class="text-muted font-monospace d-block" style="font-size: 0.65rem; letter-spacing: 2px;">RENENET EDUCARE MEMBER</small>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <!-- Empty state fallback during search/filtering -->
            <div id="noResultsState" class="text-center py-5 text-muted bg-light rounded border d-none">
                <i class="bi bi-search fs-2 mb-2 d-block text-secondary"></i>
                <span class="small">No leaders match your search query or designation filter.</span>
            </div>
        <?php endif; ?>

        <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-5">
                <ul class="pagination justify-content-center align-items-center gap-1">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link px-3" href="?page=1&search=<?php echo urlencode($search); ?>&designation=<?php echo urlencode($designation_id ?? ''); ?>">First</a>
                    </li>
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link px-3" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&designation=<?php echo urlencode($designation_id ?? ''); ?>">Previous</a>
                    </li>
                    <li class="page-item disabled mx-2">
                        <span class="text-secondary small fw-bold">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                    </li>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link px-3" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&designation=<?php echo urlencode($designation_id ?? ''); ?>">Next</a>
                    </li>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link px-3" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&designation=<?php echo urlencode($designation_id ?? ''); ?>">Last</a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<style>
.hover-lift {
    transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.hover-lift:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.08) !important;
}
.animate-avatar {
    transition: transform 0.3s ease;
}
.hover-lift:hover .animate-avatar {
    transform: scale(1.1);
}
.mt-minus-40 {
    margin-top: -50px !important;
}
.id-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.id-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 24px rgba(0,0,0,0.12) !important;
}
</style>

<!-- JS Client-side Interactivity Script -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const leaderSearch = document.getElementById('leaderSearch');
    const filterForm = document.getElementById('filterForm');
    
    if (leaderSearch && filterForm) {
        let debounceTimer = null;
        leaderSearch.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                filterForm.submit();
            }, 600); // Debounce delay of 600ms
        });

        // Focus and place cursor at the end of input to maintain continuity after reload
        const val = leaderSearch.value;
        if (val !== "") {
            leaderSearch.focus();
            leaderSearch.setSelectionRange(val.length, val.length);
        }
    }
});
</script>

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