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

$pageTitle = "Member Profile";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$member = null;

try {
    if ($pdo && $userId > 0) {
        $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
            LEFT JOIN designations d ON u.designation_id = d.id
            WHERE u.id = ? AND u.status = 'active'
        ");
        $stmt->execute([$userId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {}

if ($member) {
    $full_name = trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? '')) ?: $member['username'];
    $pageTitle = htmlspecialchars($full_name) . "'s Profile";
    
    // Set dynamic SEO meta tags
    $meta_title = htmlspecialchars($full_name) . " - Corporate " . htmlspecialchars($member['designation_title'] ?? 'Trainee');
    $meta_description = "View " . htmlspecialchars($full_name) . "'s professional network profile, team size stats, and upcoming corporate events.";
}

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

<div class="container-fluid px-0">
    <?php if (!$member): ?>
        <div class="text-center py-5 text-muted bg-white rounded border shadow-sm my-5">
            <i class="bi bi-person-x fs-2 mb-2 d-block text-danger"></i>
            <h4 class="fw-bold text-dark">Profile Not Found</h4>
            <span class="small">The leader account details you requested could not be resolved or does not exist.</span>
            <div class="mt-4">
                <a href="our_team" class="btn btn-primary"><i class="bi bi-arrow-left me-1"></i> Back to Corporate Team</a>
            </div>
        </div>
    <?php else: ?>
        <div class="mb-4">
            <a href="our_team" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-arrow-left me-1"></i> Back to Corporate Team
            </a>
        </div>

        <?php
        // Fetch direct referrals count
        $direct_team = 0;
        try {
            $stmt_team = $pdo->prepare("SELECT COUNT(*) FROM users WHERE referrer_id = ?");
            $stmt_team->execute([$member['id']]);
            $direct_team = $stmt_team->fetchColumn();
        } catch (PDOException $e) {}

        // Fetch designation history list date-wise
        $designation_history = [];
        try {
            $stmt_hist = $pdo->prepare("
                SELECT udh.achieved_at, d.title as designation_title, d.id as designation_rank
                FROM user_designation_history udh
                JOIN designations d ON udh.designation_id = d.id
                WHERE udh.user_id = ?
                ORDER BY udh.achieved_at DESC
            ");
            $stmt_hist->execute([$member['id']]);
            $designation_history = $stmt_hist->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (PDOException $e) {}

        // Fetch experiences
        $experiences = [];
        try {
            $stmt_exp = $pdo->prepare("SELECT * FROM user_experiences WHERE user_id = ? ORDER BY start_date DESC");
            $stmt_exp->execute([$member['id']]);
            $experiences = $stmt_exp->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (PDOException $e) {}

        // Fetch educations
        $educations = [];
        try {
            $stmt_edu = $pdo->prepare("SELECT * FROM user_educations WHERE user_id = ? ORDER BY start_date DESC");
            $stmt_edu->execute([$member['id']]);
            $educations = $stmt_edu->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (PDOException $e) {}

        // 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-10';
        
        if ($member['designation_rank'] >= 5) {
            $badge_class = 'bg-danger text-white';
            $icon_class = 'bi-star-fill text-danger';
            $border_color = 'border-danger';
            $header_bg = 'bg-danger bg-opacity-10';
        } elseif ($member['designation_rank'] == 4) {
            $badge_class = 'bg-warning text-dark';
            $icon_class = 'bi-award-fill text-warning';
            $border_color = 'border-warning';
            $header_bg = 'bg-warning bg-opacity-10';
        } elseif ($member['designation_rank'] == 3) {
            $badge_class = 'bg-info text-dark';
            $icon_class = 'bi-trophy-fill text-info';
            $border_color = 'border-info';
            $header_bg = 'bg-info bg-opacity-10';
        } elseif ($member['designation_rank'] == 2) {
            $badge_class = 'bg-primary text-white';
            $icon_class = 'bi-shield-fill text-primary';
            $border_color = 'border-primary';
            $header_bg = 'bg-primary bg-opacity-10';
        }
        ?>

        <div class="row g-4 mb-5">
            <!-- Profile Column (Left) -->
            <div class="col-12 col-lg-5">
                <div class="card border-0 shadow-sm overflow-hidden h-100">
                    <!-- Top header background -->
                    <div class="py-4 text-center <?php echo $header_bg; ?> border-bottom">
                        <div class="position-relative d-inline-block mb-3">
                            <?php 
                            $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=ffffff&textColor=1e293b';
                            ?>
                            <img src="<?php echo htmlspecialchars($avatar_path); ?>" 
                                 alt="Avatar" 
                                 class="rounded-circle shadow-sm border border-2 <?php echo $border_color; ?>" 
                                 style="width: 80px; height: 80px; object-fit: cover;">
                            <span class="position-absolute bottom-0 end-0 p-1 rounded-circle border border-white <?php echo $badge_class; ?>" style="width: 20px; height: 20px; transform: translate(10%, 10%);"></span>
                        </div>
                        <h4 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($full_name_seed); ?></h4>
                        <span class="badge <?php echo $badge_class; ?> font-monospace text-uppercase small" style="font-size: 0.7rem; letter-spacing: 0.5px;">
                            <?php echo htmlspecialchars($member['designation_title'] ?: 'Trainee'); ?>
                        </span>
                    </div>

                    <div class="card-body p-4">
                        <h6 class="fw-bold text-dark mb-3">Corporate Details</h6>
                        <ul class="list-group list-group-flush border rounded mb-4 overflow-hidden">
                            <li class="list-group-item d-flex justify-content-between py-2 px-3 small">
                                <span class="text-secondary">Official Email:</span>
                                <strong class="text-dark font-monospace"><?php echo htmlspecialchars($member['email']); ?></strong>
                            </li>
                            <li class="list-group-item d-flex justify-content-between py-2 px-3 small">
                                <span class="text-secondary">Joined:</span>
                                <strong class="text-dark text-end"><?php echo date('F d, Y', strtotime($member['created_at'])); ?></strong>
                            </li>
                        </ul>
                        
                        <!-- Designation Achievements Timeline History -->
                        <div class="border-top pt-4 mt-2">
                            <h6 class="fw-bold text-dark mb-3"><i class="bi bi-award-fill text-warning me-1"></i>Designation Achievements</h6>
                            <?php if (empty($designation_history)): ?>
                                <div class="text-center py-3 text-muted bg-light rounded border">
                                    <span class="small">No designation history records found.</span>
                                </div>
                            <?php else: ?>
                                <div class="list-group list-group-flush timeline-list">
                                    <?php foreach ($designation_history as $hist): ?>
                                        <?php
                                        // Set rank-specific visual styles for timeline indicators
                                        $badge_color = 'bg-secondary';
                                        if ($hist['designation_rank'] >= 5) {
                                            $badge_color = 'bg-danger text-white';
                                        } elseif ($hist['designation_rank'] == 4) {
                                            $badge_color = 'bg-warning text-dark';
                                        } elseif ($hist['designation_rank'] == 3) {
                                            $badge_color = 'bg-info text-dark';
                                        } elseif ($hist['designation_rank'] == 2) {
                                            $badge_color = 'bg-primary text-white';
                                        }
                                        ?>
                                        <div class="list-group-item bg-transparent border-0 ps-4 position-relative pb-3 pt-0">
                                            <!-- Vertical Line -->
                                            <div class="position-absolute start-0 top-0 bottom-0 ms-2 border-start border-2 border-light" style="left: 6px;"></div>
                                            <!-- Achievement Dot Indicator -->
                                            <div class="position-absolute rounded-circle <?php echo $badge_color; ?> border border-white" style="left: 0; top: 4px; width: 14px; height: 14px; box-shadow: 0 0 0 3px rgba(0,0,0,0.05);"></div>
                                            
                                            <div class="small fw-bold text-dark mb-0"><?php echo htmlspecialchars($hist['designation_title']); ?></div>
                                            <div class="text-secondary small font-monospace" style="font-size: 0.7rem;">Achieved on: <?php echo date('M d, Y \a\t g:i A', strtotime($hist['achieved_at'])); ?></div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Profile Details Column (Right) - Experience & Education -->
            <div class="col-12 col-lg-7">
                <!-- Professional Experience Card -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white border-bottom py-3">
                        <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-briefcase-fill text-primary me-2"></i>Professional Experience</h5>
                    </div>
                    <div class="card-body p-4">
                        <?php if (empty($experiences)): ?>
                            <div class="text-center py-4 text-muted">
                                <i class="bi bi-briefcase fs-3 mb-2 d-block text-secondary"></i>
                                <span class="small">No professional experience listed yet.</span>
                            </div>
                        <?php else: ?>
                            <div class="row g-3">
                                <?php foreach ($experiences as $exp): ?>
                                    <div class="col-12 border-bottom pb-3 last-border-none">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="fw-bold text-dark mb-0"><?php echo htmlspecialchars($exp['title']); ?></h6>
                                                <span class="text-secondary small d-block"><?php echo htmlspecialchars($exp['company']); ?> &bull; <?php echo htmlspecialchars($exp['location'] ?: 'Remote'); ?></span>
                                            </div>
                                            <span class="badge bg-light text-secondary border font-monospace text-uppercase small" style="font-size: 0.65rem;">
                                                <?php echo date('M Y', strtotime($exp['start_date'])); ?> - <?php echo $exp['is_current'] ? 'Present' : date('M Y', strtotime($exp['end_date'])); ?>
                                            </span>
                                        </div>
                                        <?php if (!empty($exp['description'])): ?>
                                            <p class="text-secondary small mt-2 mb-0"><?php echo nl2br(htmlspecialchars($exp['description'])); ?></p>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Academic Education Card -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-bottom py-3">
                        <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-mortarboard-fill text-success me-2"></i>Education & Qualifications</h5>
                    </div>
                    <div class="card-body p-4">
                        <?php if (empty($educations)): ?>
                            <div class="text-center py-4 text-muted">
                                <i class="bi bi-mortarboard fs-3 mb-2 d-block text-secondary"></i>
                                <span class="small">No academic history listed yet.</span>
                            </div>
                        <?php else: ?>
                            <div class="row g-3">
                                <?php foreach ($educations as $edu): ?>
                                    <div class="col-12 border-bottom pb-3 last-border-none">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="fw-bold text-dark mb-0"><?php echo htmlspecialchars($edu['degree']); ?><?php echo $edu['field_of_study'] ? ' in ' . htmlspecialchars($edu['field_of_study']) : ''; ?></h6>
                                                <span class="text-secondary small d-block"><?php echo htmlspecialchars($edu['school']); ?></span>
                                            </div>
                                            <span class="badge bg-light text-secondary border font-monospace text-uppercase small" style="font-size: 0.65rem;">
                                                <?php echo $edu['start_date'] ? date('Y', strtotime($edu['start_date'])) : ''; ?> - <?php echo $edu['end_date'] ? date('Y', strtotime($edu['end_date'])) : 'Present'; ?>
                                            </span>
                                        </div>
                                        <?php if (!empty($edu['description'])): ?>
                                            <p class="text-secondary small mt-2 mb-0"><?php echo nl2br(htmlspecialchars($edu['description'])); ?></p>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
.hover-lift {
    transition: transform 0.25s ease, box-shadow 0.25s ease;
}
.hover-lift:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 15px rgba(0,0,0,0.06) !important;
}
@keyframes pulse {
    0% { opacity: 0.9; }
    50% { opacity: 0.6; }
    100% { opacity: 0.9; }
}
.animate-pulse {
    animation: pulse 2s infinite ease-in-out;
}
</style>

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