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

$pageTitle = "Appointment Letter & ID Card";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();
$currentUser = getCurrentUser();

$user_id = $currentUser['id'];
$admin_mode = false;

// If Admin, they can view documents for any user via GET parameter
if ($currentUser['role'] === 'admin') {
    if (isset($_GET['user_id']) && !empty($_GET['user_id'])) {
        $user_id = (int)$_GET['user_id'];
        $admin_mode = true;
    }
}

// Fetch user details with designation parameters and sponsor/referrer details
try {
    $stmt_user = $pdo->prepare("
        SELECT u.*, d.title as designation_title, d.description as designation_desc, 
               d.matrix_width, d.matrix_depth, d.level_commissions, d.criteria_max_earning_cap, d.allow_wallet_payment,
               p.username as parent_name, r.username as referrer_name
        FROM users u
        LEFT JOIN designations d ON u.designation_id = d.id
        LEFT JOIN users p ON u.parent_id = p.id
        LEFT JOIN users r ON u.referrer_id = r.id
        WHERE u.id = ?
    ");
    $stmt_user->execute([$user_id]);
    $targetUser = $stmt_user->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $targetUser = null;
    $error_msg = "Database error: " . $e->getMessage();
}

if (!$targetUser) {
    // If not found, fall back to current user if we were viewing someone else
    if ($admin_mode) {
        header("Location: documents");
        exit();
    }
    die("User details not found.");
}

// If user does not have an assigned designation, fetch the default entry designation (e.g. Trainee)
if (empty($targetUser['designation_title'])) {
    try {
        $stmt_def = $pdo->query("SELECT * FROM designations WHERE is_default = TRUE LIMIT 1");
        $default_desig = $stmt_def->fetch(PDO::FETCH_ASSOC);
        if ($default_desig) {
            $targetUser['designation_title'] = $default_desig['title'];
            $targetUser['designation_desc'] = $default_desig['description'];
            $targetUser['matrix_width'] = $default_desig['matrix_width'];
            $targetUser['matrix_depth'] = $default_desig['matrix_depth'];
            $targetUser['level_commissions'] = $default_desig['level_commissions'];
            $targetUser['criteria_max_earning_cap'] = $default_desig['criteria_max_earning_cap'];
            $targetUser['allow_wallet_payment'] = $default_desig['allow_wallet_payment'] ?? false;
        } else {
            // Hardcoded defaults
            $targetUser['designation_title'] = 'Trainee';
            $targetUser['designation_desc'] = 'Entry level position.';
            $targetUser['matrix_width'] = 4;
            $targetUser['matrix_depth'] = 5;
            $targetUser['level_commissions'] = '10,5,5,10,20';
            $targetUser['criteria_max_earning_cap'] = 1000.00;
            $targetUser['allow_wallet_payment'] = false;
        }
    } catch (PDOException $e) {
        // Fallbacks
        $targetUser['designation_title'] = 'Trainee';
    }
}

// Format Name
$firstName = $targetUser['first_name'] ?? '';
$lastName = $targetUser['last_name'] ?? '';
$fullName = trim($firstName . ' ' . $lastName);
if (empty($fullName)) {
    $fullName = $targetUser['username'];
}

$designationTitle = $targetUser['designation_title'];

// Profile Photo Resolution
$avatar_exists = !empty($targetUser['profile_picture_url']) && file_exists(__DIR__ . '/' . $targetUser['profile_picture_url']);
$avatar_img = $avatar_exists 
    ? $targetUser['profile_picture_url'] 
    : 'https://ui-avatars.com/api/?name=' . urlencode($fullName) . '&background=0d6efd&color=fff&size=150';

// Fetch all users for administrator's dropdown selection
$all_users = [];
if ($currentUser['role'] === 'admin') {
    try {
        $stmt_all = $pdo->query("SELECT id, username, first_name, last_name, employee_code FROM users ORDER BY username ASC");
        $all_users = $stmt_all->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Ignore
    }
}

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

<style>
    /* Styling specifically for Corporate Documents Dashboard */
    .doc-card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        border: 1px solid rgba(0, 0, 0, 0.08);
        border-radius: 12px;
    }
    
    .nav-pills .nav-link {
        color: #495057;
        font-weight: 600;
        padding: 10px 20px;
        border-radius: 8px;
        transition: all 0.2s ease;
    }
    
    .nav-pills .nav-link.active {
        background-color: #0d6efd;
        color: #fff;
    }

    /* Print styling handles print mode elegantly */
    @media print {
        header, footer, nav, .navbar, .no-print, .btn, .nav-pills, .alert, #userSelectorCard {
            display: none !important;
        }
        html, body {
            height: auto !important;
            background-color: #fff !important;
            padding-top: 0 !important;
            margin: 0 !important;
        }
        .main-container {
            padding: 0 !important;
            margin: 0 !important;
            max-width: 100% !important;
            width: 100% !important;
        }
        .print-section.active {
            display: block !important;
            border: none !important;
            box-shadow: none !important;
            padding: 0 !important;
            margin: 0 !important;
        }
        .print-section:not(.active) {
            display: none !important;
        }
        .id-card-print-row {
            display: flex !important;
            flex-direction: row !important;
            justify-content: center !important;
            gap: 40px !important;
            margin-top: 50px !important;
        }
        .id-card-wrap {
            border: 1px solid #ddd !important;
            box-shadow: none !important;
            page-break-inside: avoid;
        }
        .appointment-letter-container {
            border: none !important;
            box-shadow: none !important;
            padding: 0 !important;
            margin: 0 !important;
            font-size: 12pt !important;
            line-height: 1.5 !important;
        }
    }
</style>

<div class="container-fluid px-md-5 my-4 main-container">
    
    <!-- Header Page Description -->
    <div class="row no-print mb-4">
        <div class="col-12">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                <div>
                    <h1 class="h2 fw-bold text-dark mb-1">Corporate Credentials & Documents</h1>
                    <p class="text-muted mb-0">View or download your designation-based appointment letter and security ID card.</p>
                </div>
                <div>
                    <a href="dashboard" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-1"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Admin Panel User Selector -->
    <?php if ($currentUser['role'] === 'admin'): ?>
        <div class="card border-0 shadow-sm mb-4 no-print" id="userSelectorCard" style="border-radius: 12px;">
            <div class="card-body bg-light rounded-3 p-3">
                <form method="GET" action="documents" class="row g-3 align-items-center">
                    <div class="col-auto">
                        <label for="user_id" class="col-form-label fw-bold text-dark"><i class="bi bi-people-fill text-primary me-2"></i>Select User to Generate For:</label>
                    </div>
                    <div class="col-12 col-md-5">
                        <select name="user_id" id="user_id" class="form-select select2-user">
                            <option value="<?php echo $currentUser['id']; ?>">-- Select Account --</option>
                            <?php foreach ($all_users as $usr): ?>
                                <?php 
                                $usr_fullname = trim(($usr['first_name'] ?? '') . ' ' . ($usr['last_name'] ?? ''));
                                $display_name = $usr['username'] . ($usr_fullname ? " ($usr_fullname)" : "") . " - " . ($usr['employee_code'] ?: 'No Code');
                                ?>
                                <option value="<?php echo $usr['id']; ?>" <?php echo $user_id === (int)$usr['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($display_name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-primary px-3"><i class="bi bi-arrow-right-circle me-1"></i>Load Credentials</button>
                    </div>
                    <?php if ($admin_mode): ?>
                        <div class="col-auto">
                            <a href="documents" class="btn btn-outline-danger">Reset to Myself</a>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <!-- Alert details if viewing someone else -->
    <?php if ($admin_mode && $targetUser): ?>
        <div class="alert alert-info border-0 shadow-sm d-flex align-items-center no-print mb-4" role="alert">
            <i class="bi bi-info-circle-fill fs-4 me-3 text-info"></i>
            <div>
                You are currently viewing corporate documents for employee <strong><?php echo htmlspecialchars($fullName); ?></strong> (Code: <code><?php echo htmlspecialchars($targetUser['employee_code'] ?: 'N/A'); ?></code>).
            </div>
        </div>
    <?php endif; ?>

    <!-- Selection Tabs (Appointment Letter / ID Card) -->
    <div class="row no-print mb-4">
        <div class="col-12">
            <ul class="nav nav-pills bg-white p-2 rounded shadow-sm d-inline-flex border" id="pills-tab" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="pills-letter-tab" data-bs-toggle="pill" data-bs-target="#pills-letter" type="button" role="tab" aria-controls="pills-letter" aria-selected="true">
                        <i class="bi bi-file-earmark-text me-1"></i> Appointment Letter
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="pills-id-tab" data-bs-toggle="pill" data-bs-target="#pills-id" type="button" role="tab" aria-controls="pills-id" aria-selected="false">
                        <i class="bi bi-person-vcard me-1"></i> Corporate ID Card
                    </button>
                </li>
            </ul>
        </div>
    </div>

    <!-- Content Sections -->
    <div class="tab-content" id="pills-tabContent">
        
        <!-- Tab 1: Appointment Letter -->
        <div class="tab-pane fade show active print-section" id="pills-letter" role="tabpanel" aria-labelledby="pills-letter-tab">
            <div class="d-flex justify-content-end mb-3 no-print">
                <button onclick="window.print();" class="btn btn-success px-4 py-2 shadow-sm fw-bold">
                    <i class="bi bi-printer-fill me-1"></i> Print / Save as PDF
                </button>
            </div>
            
            <div class="card border-0 shadow-sm p-4 p-md-5 bg-white appointment-letter-container mx-auto" style="max-width: 850px; font-family: 'Times New Roman', Georgia, serif; line-height: 1.6; color: #111; border: 1px solid rgba(0,0,0,.08) !important;">
                <!-- Letterhead Header -->
                <div class="d-flex justify-content-between align-items-center border-bottom pb-4 mb-4">
                    <div>
                        <h2 class="fw-bold text-primary mb-0 font-monospace" style="font-family: sans-serif !important;"><i class="bi bi-calendar-event-fill me-2"></i><?php echo htmlspecialchars($site_name); ?></h2>
                        <small class="text-secondary uppercase tracking-wider font-monospace" style="font-family: sans-serif !important; font-size: 0.72rem; font-weight: 700;">Corporate Hierarchy Matrix Portal</small>
                    </div>
                    <div class="text-end text-muted small" style="font-family: sans-serif !important; font-size: 0.8rem;">
                        <div>Email: support@<?php echo strtolower(str_replace(' ', '', $site_name)); ?>.com</div>
                        <div>Website: www.<?php echo strtolower(str_replace(' ', '', $site_name)); ?>.com</div>
                        <div class="mt-1 font-monospace">Ref: <strong>EP/AL/<?php echo htmlspecialchars($targetUser['employee_code'] ?: 'UNASSIGNED'); ?></strong></div>
                    </div>
                </div>
                
                <?php
                // Default Appointment Letter Template
                $default_template = <<<HTML
                <!-- Header block -->
                <div class="mb-4 text-center">
                    <h4 class="fw-bold text-dark border-bottom border-dark pb-2 d-inline-block">APPOINTMENT LETTER</h4>
                </div>

                <div class="mb-4">
                    <strong>Date:</strong> {current_date}<br>
                    <strong>Appointment Reference No.:</strong> EP/AL/{employee_code}<br>
                    <strong>Employee Name:</strong> {employee_name}<br>
                    <strong>Address:</strong> {location}
                </div>
                
                <!-- Subject -->
                <div class="mb-4">
                    <h5 class="fw-bold text-dark pb-2">
                        Subject: Appointment as {designation_title}
                    </h5>
                </div>
                
                <!-- Salutation & Body -->
                <div class="mb-4">
                    <p>Dear <strong>Mr./Ms. {first_name},</strong></p>
                    
                    <p>We are pleased to appoint you as <strong>{designation_title}</strong> with <strong>{site_name} ("the Company")</strong>. We believe your skills and experience will contribute positively to our organization.</p>
                    
                    <p>Your appointment shall be governed by the following terms and conditions.</p>
                    
                    <hr class="mb-4">

                    <h6 class="fw-bold text-dark mb-2">1. Position</h6>
                    <ul>
                        <li><strong>Designation:</strong> {designation_title}</li>
                        <li><strong>Department:</strong> Business Development / Matrix Network</li>
                        <li><strong>Reporting To:</strong> {referrer_name}</li>
                        <li><strong>Date of Joining:</strong> {joining_date}</li>
                        <li><strong>Place of Work:</strong> {location}</li>
                        <li><strong>Work Mode:</strong> Onsite / Remote / Hybrid (as assigned)</li>
                    </ul>

                    <h6 class="fw-bold text-dark mt-4 mb-2">2. Nature of Employment</h6>
                    <p>Your employment is offered on a flexible basis and may be performed outside your regular working hours with another employer, provided that:</p>
                    <ul>
                        <li>there is no conflict of interest with the Company's business;</li>
                        <li>you remain capable of fulfilling your responsibilities to the Company;</li>
                        <li>you comply with any legal or contractual obligations applicable to you.</li>
                    </ul>
                    <p>You acknowledge that you are responsible for ensuring that accepting this appointment does not breach any obligations you owe to another employer or any third party.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">3. Duties and Responsibilities</h6>
                    <p>You shall:</p>
                    <ul>
                        <li>Perform assigned duties honestly and professionally.</li>
                        <li>Complete assigned work within agreed timelines.</li>
                        <li>Maintain high standards of ethics and professionalism.</li>
                        <li>Follow Company policies, procedures, and lawful instructions.</li>
                        <li>Protect confidential and proprietary information.</li>
                        <li>Promptly report any conflict of interest.</li>
                    </ul>

                    <h6 class="fw-bold text-dark mt-4 mb-2">4. Compensation</h6>
                    <p>Your compensation shall be as follows:</p>
                    <p><strong>Base Compensation:</strong> As per performance<br>
                    <strong>Payment Frequency:</strong> As Per Minimum Payment Eligibility advance and Payment will pay between 3 to 7 th of each month<br>
                    <strong>Advance Payment:</strong> Enable to Minimum Payout once in Month and Rest Process on Last Day of Month Each Month</p>
                    
                    <p>The Company may also provide, at its sole discretion:</p>
                    <ul>
                        <li>Performance incentives.</li>
                        <li>Project completion bonuses.</li>
                        <li>Reimbursements for approved business expenses.</li>
                        <li>Other benefits or allowances, if specifically communicated in writing.</li>
                    </ul>
                    <p>All applicable taxes and statutory deductions required by law shall be deducted where applicable.</p>
                    <p>Nothing in this letter guarantees future salary revisions, bonuses, incentives, or continued engagement.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">5. Working Hours</h6>
                    <p>Working hours shall be communicated by your reporting manager depending upon operational requirements.</p>
                    <p>Additional hours may be required when necessary to complete assigned responsibilities.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">6. Confidentiality</h6>
                    <p>During and after your employment, you shall keep confidential all Company information, including but not limited to:</p>
                    <ul>
                        <li>customer information;</li>
                        <li>pricing and commercial information;</li>
                        <li>financial records;</li>
                        <li>software, source code, databases, and documentation;</li>
                        <li>business plans and strategies;</li>
                        <li>internal processes and operational information.</li>
                    </ul>
                    <p>You shall not disclose or use such information except as required for your assigned duties.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">7. Intellectual Property</h6>
                    <p>All inventions, reports, software, documentation, presentations, designs, research, data, developments, and other work products created during the course of your employment relating to Company business shall remain the exclusive property of the Company unless otherwise agreed in writing.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">8. Conflict of Interest</h6>
                    <p>You shall immediately disclose any actual or potential conflict of interest.</p>
                    <p>You shall not knowingly undertake work that directly competes with the Company's business or improperly uses the Company's confidential information.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">9. Company Liability</h6>
                    <p>To the extent permitted by applicable law:</p>
                    <ul>
                        <li>You are solely responsible for ensuring that this appointment complies with your personal legal and contractual obligations.</li>
                        <li>The Company is not responsible for disputes between you and any current or former employer, client, or third party arising from your acceptance of this appointment.</li>
                        <li>The Company shall not be liable for losses resulting from inaccurate information or declarations provided by you.</li>
                        <li>You agree to promptly notify the Company if any circumstance arises that could affect your eligibility to continue this engagement.</li>
                    </ul>
                    <p>Nothing in this clause limits any rights or obligations that cannot legally be excluded under applicable law.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">10. Code of Conduct</h6>
                    <p>You are expected to:</p>
                    <ul>
                        <li>maintain professional behavior;</li>
                        <li>comply with Company policies;</li>
                        <li>avoid harassment or discrimination;</li>
                        <li>protect Company assets;</li>
                        <li>use Company systems responsibly;</li>
                        <li>comply with applicable laws and regulations.</li>
                    </ul>

                    <h6 class="fw-bold text-dark mt-4 mb-2">11. Termination</h6>
                    <p>Either party may terminate this appointment by providing <strong>15 days' written notice</strong>, unless immediate termination is justified by misconduct, fraud, breach of confidentiality, serious policy violations, or other lawful grounds.</p>
                    <p>Upon termination, you shall immediately return all Company property, documents, credentials, equipment, and confidential information.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">12. Governing Law</h6>
                    <p>This Appointment Letter shall be governed by the applicable laws of the jurisdiction in which the Company is incorporated, and any disputes shall be subject to the jurisdiction of the competent courts unless otherwise agreed in writing.</p>

                    <h6 class="fw-bold text-dark mt-4 mb-2">13. Acceptance</h6>
                    <p>Please sign and return a copy of this Appointment Letter as confirmation of your acceptance of the terms and conditions.</p>
                    <p>We welcome you to the Company and look forward to a successful professional relationship.</p>
                </div>
                
                <hr class="mt-5 mb-4">
                
                <!-- Signatures -->
                <div class="row mt-4 pt-2">
                    <div class="col-6">
                        <h6 class="fw-bold text-dark mb-4">For the Company</h6>
                        <div class="mb-4" style="height: 25px;"></div> <!-- Signature space -->
                        <div class="border-top border-dark pt-2" style="width: 220px;">
                            <small class="text-muted d-block" style="font-family: sans-serif !important; font-size: 0.72rem;">Authorized Signatory</small>
                            <strong>Name:</strong> {site_name} HR Division<br>
                            <strong>Designation:</strong> HR Manager<br>
                            <strong>Date:</strong> {current_date}<br>
                            <strong>Company Seal:</strong> _________________
                        </div>
                    </div>
                    
                    <div class="col-6 text-end">
                        <h6 class="fw-bold text-dark mb-4">Employee Acceptance</h6>
                        <div class="d-flex flex-column align-items-end">
                            <p class="text-start text-muted mb-4" style="width: 250px; font-size: 0.85rem;">I have read, understood, and accepted the terms and conditions of this Appointment Letter.</p>
                            <div class="mb-4" style="height: 10px;"></div> <!-- Signature space -->
                            <div class="border-top border-dark pt-2 text-start" style="width: 250px;">
                                <small class="text-muted d-block" style="font-family: sans-serif !important; font-size: 0.72rem;">Employee Signature</small>
                                <strong>Employee Name:</strong> {employee_name}<br>
                                <strong>Date:</strong> ______________________<br>
                                <strong>Place:</strong> ______________________
                            </div>
                        </div>
                    </div>
                </div>
HTML;
                
                // Fetch template from DB or fallback
                $db_template = trim($site_cfg['appointment_letter_template'] ?? '');
                $template_to_render = !empty($db_template) ? $db_template : $default_template;

                // Define variable replacements map
                $replacements = [
                    '{site_name}' => htmlspecialchars($site_name),
                    '{employee_name}' => htmlspecialchars($fullName),
                    '{first_name}' => htmlspecialchars($targetUser['first_name'] ?: $targetUser['username']),
                    '{employee_code}' => htmlspecialchars($targetUser['employee_code'] ?: 'N/A'),
                    '{designation_title}' => htmlspecialchars($designationTitle),
                    '{joining_date}' => date('F d, Y', strtotime($targetUser['created_at'])),
                    '{location}' => htmlspecialchars($targetUser['location'] ?: 'Not Specified'),
                    '{email}' => htmlspecialchars($targetUser['email']),
                    '{matrix_width}' => (int)($targetUser['matrix_width'] ?? 4),
                    '{matrix_depth}' => (int)($targetUser['matrix_depth'] ?? 5),
                    '{level_commissions}' => htmlspecialchars($targetUser['level_commissions'] ?? 'N/A'),
                    '{max_earning_cap}' => number_format((float)($targetUser['criteria_max_earning_cap'] ?? 0.00), 2),
                    '{referrer_name}' => htmlspecialchars($targetUser['referrer_name'] ?: 'Corporate HR Division'),
                    '{current_date}' => date('F d, Y')
                ];

                // Parse and render
                $parsed_template = strtr($template_to_render, $replacements);
                echo $parsed_template;
                ?>
            </div>
        </div>

        <!-- Tab 2: Corporate ID Card -->
        <div class="tab-pane fade print-section" id="pills-id" role="tabpanel" aria-labelledby="pills-id-tab">
            <div class="d-flex justify-content-end mb-4 no-print">
                <button onclick="window.print();" class="btn btn-success px-4 py-2 shadow-sm fw-bold">
                    <i class="bi bi-printer-fill me-1"></i> Print ID Card Pass
                </button>
            </div>
            
            <div class="row justify-content-center id-card-print-row">
                
                <!-- FRONT SIDE -->
                <div class="col-12 col-md-6 col-lg-5 mb-4 d-flex justify-content-center">
                    <div class="id-card-wrap position-relative border shadow-sm bg-white" style="width: 325px; height: 490px; border-radius: 16px; overflow: hidden; font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; border: 1px solid rgba(0,0,0,0.12) !important;">
                        <!-- Top Header band -->
                        <div class="bg-primary text-white text-center py-3 position-relative">
                            <div class="position-absolute top-0 start-0 w-100 h-100 bg-gradient opacity-10"></div>
                            <h5 class="fw-bold text-white mb-0 uppercase tracking-wider" style="font-size: 1.05rem;"><i class="bi bi-calendar-event-fill me-2"></i><?php echo htmlspecialchars($site_name); ?></h5>
                            <small class="text-white-50 uppercase tracking-widest font-monospace" style="font-size: 0.6rem; letter-spacing: 2px;">CORPORATE MEMBER PASS</small>
                        </div>
                        
                        <!-- Accent color indicator based on role -->
                        <div class="bg-primary-subtle" style="height: 6px;"></div>

                        <!-- Card Body Details -->
                        <div class="p-4 d-flex flex-column align-items-center text-center flex-grow-1">
                            <!-- Profile picture border circles -->
                            <div class="position-relative mb-3">
                                <div class="rounded-circle bg-light border p-1" style="box-shadow: 0 4px 10px rgba(0,0,0,0.06);">
                                    <img src="<?php echo htmlspecialchars($avatar_img); ?>" class="rounded-circle" style="width: 105px; height: 105px; object-fit: cover;" alt="Profile photo">
                                </div>
                            </div>

                            <!-- User Identity Details -->
                            <h4 class="fw-bold text-dark mb-0 lh-sm"><?php echo htmlspecialchars($fullName); ?></h4>
                            
                            <!-- Designation badge -->
                            <span class="badge bg-primary text-white text-uppercase tracking-wider px-3 py-1.5 mt-2 mb-3 border font-monospace" style="font-size: 0.72rem; letter-spacing: 0.5px;">
                                <i class="bi bi-award-fill me-1"></i><?php echo htmlspecialchars($designationTitle); ?>
                            </span>

                            <!-- Meta details card -->
                            <div class="w-100 bg-light p-3 rounded-3 border mb-3">
                                <div class="row g-2 font-monospace text-start" style="font-size: 0.72rem;">
                                    <div class="col-5 text-muted uppercase">EMPLOYEE ID:</div>
                                    <div class="col-7 fw-bold text-dark"><?php echo htmlspecialchars($targetUser['employee_code'] ?: 'N/A'); ?></div>

                                    <div class="col-5 text-muted uppercase">ACCESS ROLE:</div>
                                    <div class="col-7 fw-bold text-dark text-uppercase"><?php echo htmlspecialchars($targetUser['role']); ?></div>

                                    <div class="col-5 text-muted uppercase">JOINED DATE:</div>
                                    <div class="col-7 fw-bold text-dark"><?php echo date('d M Y', strtotime($targetUser['created_at'])); ?></div>
                                </div>
                            </div>

                            <!-- Footer barcode and QR code -->
                            <div class="w-100 d-flex justify-content-between align-items-center mt-auto border-top pt-2">
                                <div class="text-start">
                                    <small class="text-muted font-monospace d-block" style="font-size: 0.58rem; letter-spacing: 0.5px;">STATUS</small>
                                    <span class="text-success fw-bold font-monospace small"><i class="bi bi-patch-check-fill me-1"></i>VERIFIED ACTIVE</span>
                                </div>
                                <div>
                                    <!-- QR Code representing user details dynamically -->
                                    <img src="https://api.qrserver.com/v1/create-qr-code/?size=55x55&data=<?php echo urlencode('EMP_CODE:' . $targetUser['employee_code'] . '|NAME:' . $fullName . '|DESIGNATION:' . $designationTitle); ?>" style="width: 55px; height: 55px; image-rendering: pixelated;" alt="QR Code">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- BACK SIDE -->
                <div class="col-12 col-md-6 col-lg-5 mb-4 d-flex justify-content-center">
                    <div class="id-card-wrap position-relative border shadow-sm bg-white" style="width: 325px; height: 490px; border-radius: 16px; overflow: hidden; font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; border: 1px solid rgba(0,0,0,0.12) !important;">
                        <!-- Header band matches front side -->
                        <div class="bg-dark text-white text-center py-3 position-relative">
                            <h6 class="fw-bold text-white mb-0 tracking-wider" style="font-size: 0.95rem;">SECURITY & TERMS OF USE</h6>
                            <small class="text-white-50 uppercase tracking-widest font-monospace" style="font-size: 0.55rem; letter-spacing: 1px;">IMPORTANT SYSTEM POLICIES</small>
                        </div>
                        
                        <!-- Top Accent strip -->
                        <div class="bg-secondary" style="height: 6px;"></div>

                        <!-- Card Body Details -->
                        <div class="p-4 d-flex flex-column flex-grow-1">
                            <div class="flex-grow-1" style="font-size: 0.72rem; color: #495057; line-height: 1.5;">
                                <p class="mb-2"><i class="bi bi-info-circle text-primary me-2"></i>This identification card is issued by <strong><?php echo htmlspecialchars($site_name); ?></strong> and is non-transferable.</p>
                                <p class="mb-2"><i class="bi bi-shield-lock text-primary me-2"></i>The holder must wear this pass during corporate events, offline sessions, and network convocations.</p>
                                <p class="mb-2"><i class="bi ban text-danger me-2"></i>Duplication, transfer, or unauthorized alteration of this credential card will result in immediate profile suspension.</p>
                                <p class="mb-3"><i class="bi bi-geo-alt text-primary me-2"></i>If found, please return this card to the corporate support desks or mail to corporate HQ.</p>
                                
                                <!-- Contact information block -->
                                <div class="bg-light p-2.5 rounded-3 border mb-3">
                                    <div class="row g-1 font-monospace text-start" style="font-size: 0.7rem;">
                                        <div class="col-4 text-muted">SUPPORT:</div>
                                        <div class="col-8 text-dark text-truncate"><?php echo htmlspecialchars($targetUser['email']); ?></div>
                                        <div class="col-4 text-muted">TELEPHONE:</div>
                                        <div class="col-8 text-dark"><?php echo htmlspecialchars($targetUser['phone'] ?: 'N/A'); ?></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Bottom HR stamp & barcode -->
                            <div class="mt-auto pt-3 border-top text-center">
                                <div class="mb-1 text-muted" style="font-family: 'Georgia', serif; font-style: italic; font-size: 0.85rem; line-height: 1;">
                                    Authorized Representative
                                </div>
                                <div style="font-size: 0.7rem; font-weight: 700; letter-spacing: 1px;" class="text-uppercase text-dark mb-3">
                                    <?php echo htmlspecialchars($site_name); ?> Executive Board
                                </div>
                                
                                <!-- CSS custom dummy barcode -->
                                <div class="mt-2 text-center">
                                    <div class="bg-dark mx-auto" style="width: 210px; height: 24px; background: repeating-linear-gradient(90deg, #000, #000 2px, #fff 2px, #fff 6px, #000 6px, #000 10px) !important;"></div>
                                    <small class="font-monospace text-muted mt-1 d-block" style="font-size: 0.58rem; letter-spacing: 0.5px;"><?php echo htmlspecialchars($targetUser['employee_code'] ?: '00000000'); ?></small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

    </div>

</div>

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