<?php
// Set flag to hide footer
$hideFooter = true;

// Fetch dependants from database
$db = Database::getInstance()->getConnection();
$stmt = $db->prepare("SELECT * FROM dependants WHERE person_id = ? AND deleted_at IS NULL ORDER BY created_at DESC");
$stmt->execute([$migrant['person_id']]);
$dependants = $stmt->fetchAll();

// Get Nigeria residence for issuance information
$nigeria_residence = $migrant['nigeria_residence'][0] ?? null;

// Get registration date (created_at from biographical_information)
$registration_date = $migrant['created_at'] ?? date('Y-m-d H:i:s');
?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-user-circle me-2" style="color: var(--nis-primary);"></i>
                    Migrant Profile
                </h2>
                <div>
                    <?php
                    $currentStatus = $migrant['current_status']['status'] ?? 'Draft';
                    $badgeClass = 'secondary';
                    switch($currentStatus) {
                        case 'Draft': $badgeClass = 'secondary'; break;
                        case 'Submitted': $badgeClass = 'warning'; break;
                        case 'Under Review': $badgeClass = 'info'; break;
                        case 'Approved': $badgeClass = 'success'; break;
                        case 'Rejected': $badgeClass = 'danger'; break;
                    }
                    ?>
                    <span class="badge bg-<?= $badgeClass ?> me-3" style="font-size: 1rem;">
                        <?= $currentStatus ?>
                    </span>
                    
                    <!-- Print Button -->
                    <button onclick="printMigrantSlip()" class="btn btn-nis me-2">
                        <i class="fas fa-print me-2"></i> Print Slip
                    </button>
                    
                    <?php if (in_array($_SESSION['user_role'] ?? '', ['ImmigrationOfficer', 'Admin', 'SuperAdmin']) && 
                              in_array($currentStatus, ['Draft', 'Rejected'])): ?>
                        <a href="<?= APP_URL ?>/migrants/<?= $migrant['person_id'] ?>/edit" 
                           class="btn btn-outline-nis me-2">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                    <?php endif; ?>
                    
                    <?php if ($currentStatus === 'Draft' && 
                              in_array($_SESSION['user_role'] ?? '', ['ImmigrationOfficer', 'Admin', 'SuperAdmin'])): ?>
                        <!--<button class="btn btn-success" onclick="submitApplication('<?= $migrant['person_id'] ?>')">-->
                        <!--    <i class="fas fa-paper-plane"></i> Submit for Review-->
                        <!--</button>-->
                    <?php endif; ?>
                    
                    <?php if (in_array($_SESSION['user_role'] ?? '', ['Admin', 'SuperAdmin']) && 
                              $currentStatus === 'Submitted'): ?>
                        <!--<button class="btn btn-primary" onclick="reviewApplication('<?= $migrant['person_id'] ?>', 'under_review')">-->
                        <!--    <i class="fas fa-check-circle"></i> Start Review-->
                        <!--</button>-->
                    <?php endif; ?>
                    
                    <?php if (in_array($_SESSION['user_role'] ?? '', ['Admin', 'SuperAdmin']) && 
                              $currentStatus === 'Under Review'): ?>
                        <!--<button class="btn btn-success" onclick="reviewApplication('<?= $migrant['person_id'] ?>', 'approve')">-->
                        <!--    <i class="fas fa-check"></i> Approve-->
                        <!--</button>-->
                        <!--<button class="btn btn-danger" onclick="reviewApplication('<?= $migrant['person_id'] ?>', 'reject')">-->
                        <!--    <i class="fas fa-times"></i> Reject-->
                        <!--</button>-->
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Person ID Card with Photo and QR Code - FIXED PHOTO DISPLAY -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <i class="fas fa-camera me-2" style="color: var(--nis-primary);"></i>
                    Migrant Photo
                </div>
                <div class="card-body text-center">
                    <?php 
                    // Check multiple possible locations for photo data
                    $photoData = null;
                    $photoFormat = 'jpeg';
                    
                    if (!empty($migrant['photo']['photo_data'])) {
                        $photoData = $migrant['photo']['photo_data'];
                        $photoFormat = $migrant['photo']['photo_format'] ?? 'jpeg';
                    } elseif (!empty($migrant['photo_data'])) {
                        $photoData = $migrant['photo_data'];
                        $photoFormat = $migrant['photo_format'] ?? 'jpeg';
                    } elseif (!empty($migrant['biometrics']) && is_array($migrant['biometrics'])) {
                        foreach ($migrant['biometrics'] as $bio) {
                            if (!empty($bio['photo_data'])) {
                                $photoData = $bio['photo_data'];
                                $photoFormat = $bio['photo_format'] ?? 'jpeg';
                                break;
                            }
                        }
                    }
                    
                    if (!empty($photoData)): 
                    ?>
                        <img src="data:image/<?= $photoFormat ?>;base64,<?= base64_encode($photoData) ?>" 
                             alt="Migrant Photo" 
                             class="img-fluid rounded" 
                             style="max-width: 200px; max-height: 200px; border: 3px solid var(--nis-primary);">
                        <p class="text-success mt-2">
                            <i class="fas fa-check-circle"></i> Photo Captured
                        </p>
                    <?php else: ?>
                        <div class="bg-light rounded d-flex align-items-center justify-content-center mx-auto" style="width: 150px; height: 150px;">
                            <i class="fas fa-user fa-5x text-muted"></i>
                        </div>
                        <p class="text-warning mt-2">
                            <i class="fas fa-exclamation-triangle"></i> No photo captured
                        </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <i class="fas fa-id-card me-2" style="color: var(--nis-primary);"></i>
                    Migrant Details
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Person ID</small>
                            <div class="h5"><code><?= $migrant['person_id'] ?></code></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Full Name</small>
                            <div class="h5"><?= $migrant['surname'] ?>, <?= $migrant['given_name'] ?></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Document No</small>
                            <div class="h6"><?= $migrant['document_no'] ?></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Nationality</small>
                            <div class="h6"><?= $migrant['nationality'] ?></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Date of Birth</small>
                            <div class="h6"><?= date('d/m/Y', strtotime($migrant['date_of_birth'])) ?></div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <small class="text-muted d-block">Sex</small>
                            <div class="h6"><?= $migrant['sex'] ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <i class="fas fa-qrcode me-2" style="color: var(--nis-primary);"></i>
                    QR Code
                </div>
                <div class="card-body text-center">
                    <div id="profile-qrcode" style="display: inline-block;"></div>
                    <p class="text-muted mt-2 small">Scan for quick access</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Biometrics Information Card -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-white">
                    <i class="fas fa-fingerprint me-2" style="color: var(--nis-primary);"></i>
                    Biometrics Information
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- Fingerprint Summary -->
                        <div class="col-md-6">
                            <h6 class="text-success mb-3"><i class="fas fa-fingerprint me-2"></i>Fingerprints Captured</h6>
                            <?php if (!empty($migrant['fingerprints'])): ?>
                                <?php
                                $fingerCount = count($migrant['fingerprints']);
                                $fingerPositions = array_column($migrant['fingerprints'], 'finger_position');
                                ?>
                                <div class="row">
                                    <div class="col-6">
                                        <small class="text-muted d-block">Left Hand</small>
                                        <ul class="list-unstyled">
                                            <?php
                                            $leftFingers = ['Left Thumb', 'Left Index', 'Left Middle', 'Left Ring', 'Left Little'];
                                            foreach ($leftFingers as $finger):
                                                $captured = in_array($finger, $fingerPositions);
                                            ?>
                                            <li class="<?= $captured ? 'text-success' : 'text-muted' ?>">
                                                <i class="fas fa-<?= $captured ? 'check-circle' : 'circle' ?> me-1"></i>
                                                <?= $finger ?>
                                            </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted d-block">Right Hand</small>
                                        <ul class="list-unstyled">
                                            <?php
                                            $rightFingers = ['Right Thumb', 'Right Index', 'Right Middle', 'Right Ring', 'Right Little'];
                                            foreach ($rightFingers as $finger):
                                                $captured = in_array($finger, $fingerPositions);
                                            ?>
                                            <li class="<?= $captured ? 'text-success' : 'text-muted' ?>">
                                                <i class="fas fa-<?= $captured ? 'check-circle' : 'circle' ?> me-1"></i>
                                                <?= $finger ?>
                                            </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </div>
                                <hr>
                                <p class="mb-0 text-center">
                                    <span class="badge bg-success"><?= $fingerCount ?> / 10 fingerprints captured</span>
                                </p>
                            <?php else: ?>
                                <p class="text-warning text-center mb-0">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    No fingerprints captured
                                </p>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Additional biometrics info -->
                        <div class="col-md-6">
                            <h6 class="text-success mb-3"><i class="fas fa-info-circle me-2"></i>Biometrics Status</h6>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Biometrics captured:</strong> 
                                <?= (!empty($migrant['photo']['photo_data']) ? 'Photo ✓' : 'Photo ✗') ?>, 
                                <?= (!empty($migrant['fingerprints']) ? 'Fingerprints ✓' : 'Fingerprints ✗') ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- DEPENDANT INFORMATION SECTION -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-users me-2" style="color: var(--nis-primary);"></i>
                        Dependant Information
                    </div>
                    <button type="button" class="btn btn-sm btn-nis" onclick="toggleDependantForm()">
                        <i class="fas fa-plus-circle me-1"></i> Add Dependant
                    </button>
                </div>
                <div class="card-body">
                    <!-- Add Dependant Form (Hidden by default) -->
                    <div id="add-dependant-form" style="display: none;" class="mb-4 p-3 border rounded bg-light">
                        <h6 class="text-success mb-3"><i class="fas fa-user-plus me-2"></i>Add New Dependant</h6>
                        <form id="dependantForm" method="POST" action="<?= APP_URL ?>/migrants/add-dependant">
                            <input type="hidden" name="person_id" value="<?= $migrant['person_id'] ?>">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?? '' ?>">
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">SURNAME <span class="text-danger">*</span></label>
                                    <input type="text" name="surname" class="form-control text-uppercase" required>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">GIVEN NAME <span class="text-danger">*</span></label>
                                    <input type="text" name="given_name" class="form-control text-uppercase" required>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">DATE OF BIRTH <span class="text-danger">*</span></label>
                                    <input type="date" name="date_of_birth" class="form-control" required>
                                    <small class="text-muted">Dependant must be under 18 years old</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">GENDER <span class="text-danger">*</span></label>
                                    <select name="gender" class="form-select" required>
                                        <option value="">SELECT GENDER</option>
                                        <option value="Male">MALE</option>
                                        <option value="Female">FEMALE</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">DOCUMENT NO (Optional)</label>
                                    <input type="text" name="document_no" class="form-control">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">RELATIONSHIP <span class="text-danger">*</span></label>
                                    <select name="relationship" class="form-select" required>
                                        <option value="">SELECT RELATIONSHIP</option>
                                        <option value="Child">Child</option>
                                        <option value="Adopted Child">Adopted Child</option>
                                        <option value="Ward">Ward</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="text-end">
                                <button type="button" class="btn btn-outline-secondary me-2" onclick="toggleDependantForm()">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </button>
                                <button type="submit" class="btn btn-nis">
                                    <i class="fas fa-save me-1"></i> Save Dependant
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Dependants List -->
                    <div id="dependants-list">
                        <?php if (empty($dependants)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No dependants added yet.</p>
                                <button type="button" class="btn btn-sm btn-outline-nis" onclick="toggleDependantForm()">
                                    <i class="fas fa-plus-circle me-1"></i> Add First Dependant
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Surname</th>
                                            <th>Given Name</th>
                                            <th>Date of Birth</th>
                                            <th>Gender</th>
                                            <th>Document No</th>
                                            <th>Relationship</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($dependants as $dep): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($dep['surname']) ?></td>
                                            <td><?= htmlspecialchars($dep['given_name']) ?></td>
                                            <td><?= date('d/m/Y', strtotime($dep['date_of_birth'])) ?></td>
                                            <td><?= $dep['gender'] ?></td>
                                            <td><?= $dep['document_no'] ?? 'N/A' ?></td>
                                            <td><span class="badge bg-info"><?= $dep['relationship'] ?></span></td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-outline-danger" 
                                                        onclick="deleteDependant(<?= $dep['id'] ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Foreign Address & Nigeria Residence -->
    <div class="row">
        <div class="col-md-6">
            <?php if (!empty($migrant['foreign_address'])): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-globe"></i> Foreign Address
                </div>
                <div class="card-body">
                    <?php foreach ($migrant['foreign_address'] as $addr): ?>
                    <table class="table table-sm">
                        <tr><th width="40%">Country:</th><td><?= $addr['country'] ?? 'N/A' ?></td></tr>
                        <tr><th>State/Province:</th><td><?= $addr['state_province'] ?? 'N/A' ?></td></tr>
                        <tr><th>Town:</th><td><?= $addr['town'] ?? 'N/A' ?></td></tr>
                        <tr><th>Postal Code:</th><td><?= $addr['postal_code'] ?? 'N/A' ?></td></tr>
                        <tr><th>Address:</th><td><?= nl2br($addr['abroad_address']) ?></td></tr>
                        <tr><th>Phone:</th><td><?= $addr['phone_number'] ?? 'N/A' ?></td></tr>
                    </table>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($migrant['nigeria_residence'])): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-map-marker-alt"></i> Nigeria Residence
                </div>
                <div class="card-body">
                    <?php foreach ($migrant['nigeria_residence'] as $res): ?>
                    <table class="table table-sm">
                        <tr><th width="40%">State:</th><td><?= $res['state'] ?? 'N/A' ?></td></tr>
                        <tr><th>LGA:</th><td><?= $res['local_government'] ?? 'N/A' ?></td></tr>
                        <tr><th>Town:</th><td><?= $res['town'] ?? 'N/A' ?></td></tr>
                        <tr><th>Address:</th><td><?= nl2br($res['address']) ?></td></tr>
                        <tr><th>Phone:</th><td><?= $res['phone_number'] ?? 'N/A' ?></td></tr>
                        <tr><th>Reference:</th><td><?= $res['reference_person_name'] ?? 'N/A' ?></td></tr>
                    </table>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="col-md-6">
            <!-- Employment History -->
            <?php if (!empty($migrant['employment'])): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-briefcase"></i> Employment History
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Employer</th>
                                    <th>Job Title</th>
                                    <th>Start Date</th>
                                    <th>End Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($migrant['employment'] as $emp): ?>
                                <tr>
                                    <td><?= $emp['employer_name'] ?></td>
                                    <td><?= $emp['job_title'] ?></td>
                                    <td><?= date('d/m/Y', strtotime($emp['start_date'])) ?></td>
                                    <td><?= $emp['end_date'] ? date('d/m/Y', strtotime($emp['end_date'])) : 'Current' ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Immigrant Status -->
            <?php if (!empty($migrant['immigrant_status'])): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-passport"></i> Immigrant Status
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Category</th>
                                    <th>Visa Type</th>
                                    <th>Permit No</th>
                                    <th>Date Granted</th>
                                    <th>Expiry Date</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($migrant['immigrant_status'] as $status): ?>
                                <tr>
                                    <td><?= $status['status_category'] ?></td>
                                    <td><?= $status['visa_type'] ?? 'N/A' ?></td>
                                    <td><?= $status['permit_number'] ?? 'N/A' ?></td>
                                    <td><?= date('d/m/Y', strtotime($status['date_granted'])) ?></td>
                                    <td><?= $status['expiry_date'] ? date('d/m/Y', strtotime($status['expiry_date'])) : 'N/A' ?></td>
                                    <td><span class="badge bg-<?= $status['is_active'] ? 'success' : 'secondary' ?>"><?= $status['is_active'] ? 'Active' : 'Inactive' ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Travel History -->
    <?php if (!empty($migrant['travel_history'])): ?>
    <div class="row">
        <div class="col-12">
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-plane"></i> Travel History
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Purpose</th>
                                    <th>Departure</th>
                                    <th>Arrival</th>
                                    <th>From</th>
                                    <th>Transport</th>
                                    <th>Port of Entry</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($migrant['travel_history'] as $travel): ?>
                                <tr>
                                    <td><?= $travel['purpose_of_travel'] ?></td>
                                    <td><?= date('d/m/Y', strtotime($travel['departure_date'])) ?></td>
                                    <td><?= date('d/m/Y', strtotime($travel['arrival_date'])) ?></td>
                                    <td><?= $travel['departure_country'] ?></td>
                                    <td><?= $travel['transportation_type'] ?></td>
                                    <td><?= $travel['port_of_entry'] ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Medical History -->
    <?php if (!empty($migrant['medical_history'])): ?>
    <div class="row">
        <div class="col-12">
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-heartbeat"></i> Medical History
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Illness</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    <th>Vaccine</th>
                                    <th>Vaccine Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($migrant['medical_history'] as $med): ?>
                                <tr>
                                    <td><?= $med['illness_name'] ?></td>
                                    <td><?= $med['illness_date'] ? date('d/m/Y', strtotime($med['illness_date'])) : 'N/A' ?></td>
                                    <td><span class="badge bg-<?= $med['is_current'] ? 'warning' : 'secondary' ?>"><?= $med['is_current'] ? 'Current' : 'Past' ?></span></td>
                                    <td><?= $med['vaccine_name'] ?></td>
                                    <td><?= $med['vaccine_date'] ? date('d/m/Y', strtotime($med['vaccine_date'])) : 'N/A' ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Uploaded Documents -->
    <?php if (!empty($migrant['documents'])): ?>
    <div class="row">
        <div class="col-12">
            <div class="card mb-4">
                <div class="card-header">
                    <i class="fas fa-file-alt"></i> Uploaded Documents
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Document</th>
                                    <th>Type</th>
                                    <th>Size</th>
                                    <th>Uploaded By</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($migrant['documents'] as $doc): ?>
                                <tr>
                                    <td><?= $doc['file_name'] ?></td>
                                    <td><?= $doc['document_type'] ?></td>
                                    <td><?= round($doc['file_size'] / 1024, 2) ?> KB</td>
                                    <td><?= $doc['uploaded_by'] ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($doc['created_at'])) ?></td>
                                    <td><a href="<?= $doc['file_path'] ?>" class="btn btn-sm btn-outline-nis" download><i class="fas fa-download"></i></a></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Application Timeline -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-white">
                    <div class="d-flex align-items-center">
                        <div class="rounded-circle bg-info p-3 me-3" style="width: 50px; height: 50px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-history text-white fa-2x"></i>
                        </div>
                        <div>
                            <h5 class="mb-0">Application Timeline</h5>
                            <small class="text-muted">Complete history of this application</small>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($migrant['status_history'])): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-clock fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No status history available</p>
                        </div>
                    <?php else: ?>
                        <div class="timeline">
                            <?php foreach ($migrant['status_history'] as $status): ?>
                                <?php
                                $statusColor = '';
                                $statusIcon = '';
                                switch($status['status']) {
                                    case 'Draft': $statusColor = 'secondary'; $statusIcon = 'fa-pencil-alt'; break;
                                    case 'Submitted': $statusColor = 'warning'; $statusIcon = 'fa-paper-plane'; break;
                                    case 'Under Review': $statusColor = 'info'; $statusIcon = 'fa-search'; break;
                                    case 'Approved': $statusColor = 'success'; $statusIcon = 'fa-check-circle'; break;
                                    case 'Rejected': $statusColor = 'danger'; $statusIcon = 'fa-times-circle'; break;
                                    default: $statusColor = 'secondary'; $statusIcon = 'fa-circle';
                                }
                                ?>
                                <div class="timeline-item mb-4">
                                    <div class="d-flex">
                                        <div class="timeline-icon me-3">
                                            <div class="rounded-circle bg-<?= $statusColor ?> p-3" style="width: 50px; height: 50px; display: flex; align-items: center; justify-content: center;">
                                                <i class="fas <?= $statusIcon ?> text-white"></i>
                                            </div>
                                        </div>
                                        <div class="timeline-content flex-grow-1">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <h6 class="mb-0"><span class="badge bg-<?= $statusColor ?>" style="font-size: 1rem;"><?= $status['status'] ?></span></h6>
                                                <small class="text-muted"><i class="fas fa-calendar-alt me-1"></i><?= date('d/m/Y H:i', strtotime($status['created_at'])) ?></small>
                                            </div>
                                            <?php if (!empty($status['remarks'])): ?>
                                                <div class="alert alert-light border-start border-<?= $statusColor ?> border-4 py-2 mb-2">
                                                    <i class="fas fa-quote-left me-2 text-muted"></i><?= htmlspecialchars($status['remarks']) ?>
                                                </div>
                                            <?php endif; ?>
                                            <div class="d-flex align-items-center">
                                                <i class="fas fa-user-circle me-2 text-muted"></i>
                                                <small class="text-muted">By: <strong><?= htmlspecialchars($status['reviewer_name'] ?? 'System') ?></strong></small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- PRINT SLIP AREA - A6 LANDSCAPE (148mm × 105mm) -->
<div id="print-slip" style="display: none;">
    <style>
        @media print {
            @page {
                size: 148mm 105mm; /* A6 landscape (width × height) */
                margin: 3mm;
            }
            
            body * { visibility: hidden; }
            #print-slip, #print-slip * { visibility: visible; }
            
            #print-slip {
                position: absolute;
                left: 0;
                top: 0;
                width: 148mm;
                height: 105mm;
                background: white;
                font-family: 'Segoe UI', Arial, sans-serif;
                font-size: 8pt;
                padding: 2.5mm;
                box-sizing: border-box;
                overflow: hidden;
                page-break-after: avoid;
                page-break-inside: avoid;
            }
            
            .slip-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 2mm;
                border-bottom: 1.5px solid #006747;
                padding-bottom: 1.5mm;
                height: 21mm;
            }
            
            .slip-photo {
                width: 19mm;
                height: 19mm;
                border: 1px solid #006747;
                border-radius: 2px;
                overflow: hidden;
                background: #f5f5f5;
                flex-shrink: 0;
            }
            
            .slip-photo img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
            
            .slip-photo-placeholder {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f0f0f0;
                color: #999;
                font-size: 16px;
            }
            
            .slip-title {
                text-align: center;
                flex-grow: 1;
                padding: 0 1.5mm;
                margin-top: -2mm;
            }
            
            .slip-title img {
                max-height: 11mm;
                margin-bottom: 0.5mm;
            }
            
            .slip-title h1 {
                color: #006747;
                margin: 0;
                font-size: 10pt;
                font-weight: bold;
                line-height: 1.1;
            }
            
            .slip-title p {
                color: #006747;
                margin: 0;
                font-size: 9pt;
                font-weight: bold;
            }
            
            .slip-qrcode {
                width: 21mm;
                height: 21mm;
                text-align: right;
                flex-shrink: 0;
                margin-top: -2.5mm;
            }
            
            .slip-qrcode img {
                width: 21mm;
                height: 21mm;
                image-rendering: -webkit-optimize-contrast;
                image-rendering: crisp-edges;
                image-rendering: pixelated;
            }
            
            .slip-sections-container {
                display: flex;
                gap: 1.5mm;
                height: 60mm;
                margin-bottom: 1.5mm;
            }
            
            .slip-section {
                flex: 1;
                border: 1px solid #ddd;
                border-radius: 2px;
                padding: 1.5mm;
                overflow: hidden;
                display: flex;
                flex-direction: column;
                position: relative; /* For watermark positioning */
            }
            
            .slip-section h2 {
                color: #006747;
                font-size: 8.5pt;
                margin: 0 0 1mm 0;
                padding-bottom: 0.5mm;
                border-bottom: 1px solid #006747;
                text-align: center;
                flex-shrink: 0;
                position: relative;
                z-index: 2;
            }
            
            .slip-section-content {
                flex-grow: 1;
                overflow: visible;
                display: flex;
                flex-direction: column;
                gap: 1mm;
                position: relative;
                z-index: 2;
            }
            
            /* Watermark styles for PERSONAL INFORMATION and DOCUMENT INFORMATION sections */
            .slip-section.watermark-left::before {
                content: '';
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 100%;
                height: 100%;
                background-image: url('<?= APP_URL ?>/public/assets/images/nis-logo.png');
                background-repeat: no-repeat;
                background-position: center;
                background-size: 80% auto;
                opacity: 0.15; /* Very subtle watermark */
                pointer-events: none;
                z-index: 1;
            }
            
            .slip-field {
                width: 100%;
                flex-shrink: 0;
            }
            
            .slip-label {
                font-weight: bold;
                color: #006747;
                font-size: 6.5pt;
                display: block;
                margin-bottom: 0.3mm;
                text-transform: uppercase;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            
            .slip-value {
                color: #000;
                font-size: 7pt;
                display: block;
                padding-left: 0.8mm;
                border-left: 1.5px solid #006747;
                word-break: break-word;
                line-height: 1.2;
                white-space: normal;
                overflow: visible;
                min-height: 3mm;
            }
            
            .slip-nis-logo {
                text-align: center;
                margin-top: 2mm;
                padding: 1mm;
                background-color: transparent;
                border-radius: 2px;
                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;
                z-index: 2;
            }
            
            .slip-nis-logo img {
                max-width: 100%;
                max-height: 18mm;
                width: auto;
                height: auto;
                object-fit: contain;
            }
            
            .slip-footer {
                text-align: center;
                font-size: 5.5pt;
                color: #666;
                border-top: 1px solid #ddd;
                padding-top: 0.8mm;
                height: 7mm;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 1.5mm;
                flex-shrink: 0;
            }
            
            .slip-footer img {
                max-height: 4mm;
                width: auto;
            }
            
            .slip-footer p {
                margin: 0;
            }
        }
    </style>
    
    <div id="slip-content">
        <!-- Header with Photo, Title and QR Code -->
        <div class="slip-header">
            <div class="slip-photo">
                <?php 
                // Check multiple possible locations for photo data in print slip
                $printPhotoData = null;
                $printPhotoFormat = 'jpeg';
                
                if (!empty($migrant['photo']['photo_data'])) {
                    $printPhotoData = $migrant['photo']['photo_data'];
                    $printPhotoFormat = $migrant['photo']['photo_format'] ?? 'jpeg';
                } elseif (!empty($migrant['photo_data'])) {
                    $printPhotoData = $migrant['photo_data'];
                    $printPhotoFormat = $migrant['photo_format'] ?? 'jpeg';
                } elseif (!empty($migrant['biometrics']) && is_array($migrant['biometrics'])) {
                    foreach ($migrant['biometrics'] as $bio) {
                        if (!empty($bio['photo_data'])) {
                            $printPhotoData = $bio['photo_data'];
                            $printPhotoFormat = $bio['photo_format'] ?? 'jpeg';
                            break;
                        }
                    }
                }
                
                if (!empty($printPhotoData)): 
                ?>
                    <img src="data:image/<?= $printPhotoFormat ?>;base64,<?= base64_encode($printPhotoData) ?>" 
                         alt="Migrant Photo">
                <?php else: ?>
                    <div class="slip-photo-placeholder">
                        <i class="fas fa-user"></i>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="slip-title">
                <img src="<?= APP_URL ?>/public/assets/images/coat-of-arms.png" alt="Coat of Arms">
                <h1>FEDERAL REPUBLIC OF NIGERIA</h1>
                <p>MIGRANT e-REGISTRATION SLIP</p>
            </div>
            
            <div class="slip-qrcode" id="slip-qrcode"></div>
        </div>
        
        <!-- Three Sections Side by Side -->
        <div class="slip-sections-container">
            <!-- SECTION 1: PERSONAL INFORMATION (with watermark) - UPDATED with Person ID -->
            <div class="slip-section watermark-left">
                <h2>PERSONAL INFORMATION</h2>
                <div class="slip-section-content">
                    <!-- Person ID added here - BEFORE FULL NAME -->
                    <div class="slip-field">
                        <span class="slip-label">PERSON ID</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['person_id'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">FULL NAME</span>
                        <span class="slip-value"><?= htmlspecialchars(($migrant['surname'] ?? '') . ' ' . ($migrant['given_name'] ?? '')) ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">DATE OF BIRTH</span>
                        <span class="slip-value"><?= isset($migrant['date_of_birth']) ? date('d/m/Y', strtotime($migrant['date_of_birth'])) : 'N/A' ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">SEX</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['sex'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">NATIONALITY</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['nationality'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">OCCUPATION</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['occupation'] ?? 'N/A') ?></span>
                    </div>
                </div>
            </div>
            
            <!-- SECTION 2: DOCUMENT INFORMATION (with watermark) -->
            <div class="slip-section watermark-left">
                <h2>DOCUMENT INFORMATION</h2>
                <div class="slip-section-content">
                    <div class="slip-field">
                        <span class="slip-label">DOCUMENT TYPE</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['document_type'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">DOCUMENT NUMBER</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['document_no'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">COUNTRY OF ISSUE</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['country_of_issue'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">ISSUE DATE</span>
                        <span class="slip-value"><?= isset($migrant['date_of_issue']) ? date('d/m/Y', strtotime($migrant['date_of_issue'])) : 'N/A' ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">EXPIRY DATE</span>
                        <span class="slip-value"><?= isset($migrant['expiry_date']) ? date('d/m/Y', strtotime($migrant['expiry_date'])) : 'N/A' ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">ISSUING AUTHORITY</span>
                        <span class="slip-value"><?= htmlspecialchars($migrant['issuing_authority'] ?? 'N/A') ?></span>
                    </div>
                </div>
            </div>
            
            <!-- SECTION 3: ISSUANCE INFORMATION (with main logo) -->
            <div class="slip-section">
                <h2>ISSUANCE INFORMATION</h2>
                <div class="slip-section-content">
                    <div class="slip-field">
                        <span class="slip-label">STATE</span>
                        <span class="slip-value"><?= htmlspecialchars($nigeria_residence['state'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">LOCAL GOVERNMENT AREA</span>
                        <span class="slip-value"><?= htmlspecialchars($nigeria_residence['local_government'] ?? 'N/A') ?></span>
                    </div>
                    <div class="slip-field">
                        <span class="slip-label">DATE OF ISSUE</span>
                        <span class="slip-value"><?= date('d/m/Y', strtotime($registration_date)) ?></span>
                    </div>
                    
                    <!-- NIS Logo - BIG (18mm) and TRANSPARENT -->
                    <div class="slip-nis-logo">
                        <img src="<?= APP_URL ?>/public/assets/images/nis-logo.png" alt="NIS Logo">
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Footer with NIS Logo -->
        <div class="slip-footer">
            <img src="<?= APP_URL ?>/public/assets/images/nis-logo.png" alt="NIS Logo">
            <p>Nigeria Immigration Service </p>
        </div>
    </div>
</div>

<!-- Load QR Library -->
<script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
<!-- Load jQuery (if not already loaded) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
// Generate QR code for profile
document.addEventListener('DOMContentLoaded', function() {
    // Generate profile QR code
    const profileQr = document.getElementById('profile-qrcode');
    if (profileQr && typeof qrcode !== 'undefined') {
        const qrData = {
            id: '<?= addslashes($migrant['person_id'] ?? '') ?>',
            name: '<?= addslashes(($migrant['surname'] ?? '') . ', ' . ($migrant['given_name'] ?? '')) ?>'
        };
        
        const qr = qrcode(0, 'M');
        qr.addData(JSON.stringify(qrData));
        qr.make();
        profileQr.innerHTML = qr.createImgTag(3);
        
        // Style the QR image
        const img = profileQr.querySelector('img');
        if (img) {
            img.style.width = '150px';
            img.style.height = '150px';
        }
    }
    
    // Add client-side age validation
    const dobInput = document.querySelector('input[name="date_of_birth"]');
    if (dobInput) {
        dobInput.addEventListener('change', function() {
            validateAge(this);
        });
    }
});

// Client-side age validation function
function validateAge(input) {
    const selectedDate = new Date(input.value);
    const today = new Date();
    const eighteenYearsAgo = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate());
    
    if (selectedDate > eighteenYearsAgo) {
        // Person is under 18 - valid
        input.setCustomValidity('');
    } else {
        // Person is 18 or older - invalid
        input.setCustomValidity('Dependant must be under 18 years old');
        input.reportValidity();
    }
}

// ==================== PRINT SLIP FUNCTION (A6 SIZE) ====================
function printMigrantSlip() {
    console.log("Print slip function started");
    
    // Get the print area
    const printArea = document.getElementById('print-slip');
    const qrContainer = document.getElementById('slip-qrcode');
    
    if (!printArea) {
        alert('Print area not found');
        return;
    }
    
    // Clear previous QR
    if (qrContainer) {
        qrContainer.innerHTML = '';
    }
    
    // Generate QR code with migrant data - HIGHER QUALITY FOR SCANNABILITY
    try {
        const qrData = {
            id: '<?= addslashes($migrant['person_id'] ?? '') ?>',
            name: '<?= addslashes(($migrant['surname'] ?? '') . ' ' . ($migrant['given_name'] ?? '')) ?>',
            dob: '<?= addslashes($migrant['date_of_birth'] ?? '') ?>',
            doc: '<?= addslashes($migrant['document_no'] ?? '') ?>',
            nationality: '<?= addslashes($migrant['nationality'] ?? '') ?>'
        };
        
        console.log("QR Data:", qrData);
        
        if (typeof qrcode !== 'undefined' && qrContainer) {
            // Use HIGHER ERROR CORRECTION for better scannability
            const qr = qrcode(0, 'H'); // 'H' = High error correction (30%)
            qr.addData(JSON.stringify(qrData));
            qr.make();
            
            // Create larger QR code for better scanning
            qrContainer.innerHTML = qr.createImgTag(6); // Increased from 4 to 6 for higher resolution
            
            // Style the QR image
            const img = qrContainer.querySelector('img');
            if (img) {
                img.style.width = '22mm';
                img.style.height = '22mm';
                img.style.imageRendering = 'pixelated'; // Keep pixels sharp
            }
        }
    } catch (e) {
        console.error("QR Error:", e);
    }
    
    // Show print area and print
    printArea.style.display = 'block';
    
    setTimeout(function() {
        window.print();
        printArea.style.display = 'none';
    }, 300);
}

// ==================== EXISTING FUNCTIONS ====================
function submitApplication(personId) {
    if (confirm('Are you sure you want to submit this application for review?')) {
        $.post('<?= APP_URL ?>/migrants/' + personId + '/submit', {
            csrf_token: '<?= $_SESSION['csrf_token'] ?>'
        }, function(response) {
            if (response.success) {
                alert(response.message);
                location.reload();
            } else {
                alert('Error: ' + response.error);
            }
        }).fail(function(xhr) {
            alert('Error: ' + (xhr.responseJSON?.error || 'Unknown error'));
        });
    }
}

function reviewApplication(personId, action) {
    let message = action === 'approve' ? 'Approve this application?' : 
                  action === 'reject' ? 'Reject this application?' : 
                  'Start reviewing this application?';
    
    let remarks = '';
    if (action === 'approve' || action === 'reject') {
        remarks = prompt('Enter remarks:');
        if (remarks === null) return;
    }
    
    if (confirm(message)) {
        $.post('<?= APP_URL ?>/migrants/' + personId + '/review', {
            action: action,
            remarks: remarks,
            csrf_token: '<?= $_SESSION['csrf_token'] ?>'
        }, function(response) {
            if (response.success) {
                alert(response.message);
                location.reload();
            } else {
                alert('Error: ' + response.error);
            }
        }).fail(function(xhr) {
            alert('Error: ' + (xhr.responseJSON?.error || 'Unknown error'));
        });
    }
}

// =============================================
// DEPENDANT INFORMATION FUNCTIONS
// =============================================

// Toggle the add dependant form
function toggleDependantForm() {
    const form = document.getElementById('add-dependant-form');
    if (form.style.display === 'none') {
        form.style.display = 'block';
        // Scroll to form
        form.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        form.style.display = 'none';
        // Reset form
        document.getElementById('dependantForm').reset();
    }
}

// Handle dependant form submission with jQuery AJAX
$('#dependantForm').on('submit', function(e) {
    e.preventDefault();
    
    // Log form data for debugging
    console.log('Form submitted');
    
    // Get form data
    const formData = $(this).serialize();
    console.log('Form data:', formData);
    
    // Show loading state
    const submitBtn = $(this).find('button[type="submit"]');
    const originalText = submitBtn.html();
    submitBtn.html('<i class="fas fa-spinner fa-spin me-1"></i> Saving...').prop('disabled', true);
    
    // Send AJAX request
    $.ajax({
        url: '<?= APP_URL ?>/migrants/add-dependant',
        type: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            console.log('Success response:', response);
            
            if (response.success) {
                alert(response.message || 'Dependant added successfully');
                
                // Hide form and reset
                $('#add-dependant-form').hide();
                $('#dependantForm')[0].reset();
                
                // Reload the page to show the new dependant
                location.reload();
            } else {
                alert('Error: ' + (response.error || 'Unknown error occurred'));
                // Reset button
                submitBtn.html(originalText).prop('disabled', false);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error Status:', status);
            console.error('AJAX Error:', error);
            console.error('Response Text:', xhr.responseText);
            console.error('Response Status:', xhr.status);
            
            let errorMsg = 'Error adding dependant. ';
            
            // Try to parse error response
            try {
                const response = JSON.parse(xhr.responseText);
                console.error('Parsed error response:', response);
                errorMsg += response.error || response.message || 'Please try again.';
            } catch(e) {
                console.error('Could not parse response:', e);
                errorMsg += 'Server returned: ' + xhr.status + ' ' + xhr.statusText;
                
                // Show raw response for debugging
                if (xhr.responseText) {
                    console.log('Raw response:', xhr.responseText);
                    errorMsg += ' Check console for details.';
                }
            }
            
            alert(errorMsg);
            
            // Reset button
            submitBtn.html(originalText).prop('disabled', false);
        }
    });
});

// Load dependants via AJAX
function loadDependants() {
    $.ajax({
        url: '<?= APP_URL ?>/migrants/get-dependants/<?= $migrant['person_id'] ?>',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                updateDependantsList(response.data);
            }
        },
        error: function(xhr) {
            console.error('Error loading dependants');
        }
    });
}

// Update the dependants list in the DOM
function updateDependantsList(dependants) {
    const container = document.getElementById('dependants-list');
    
    if (!dependants || dependants.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <p class="text-muted">No dependants added yet.</p>
                <button type="button" class="btn btn-sm btn-outline-nis" onclick="toggleDependantForm()">
                    <i class="fas fa-plus-circle me-1"></i> Add First Dependant
                </button>
            </div>
        `;
        return;
    }
    
    let html = `
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Surname</th>
                        <th>Given Name</th>
                        <th>Date of Birth</th>
                        <th>Gender</th>
                        <th>Document No</th>
                        <th>Relationship</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    dependants.forEach(dep => {
        html += `
            <tr>
                <td>${escapeHtml(dep.surname)}</td>
                <td>${escapeHtml(dep.given_name)}</td>
                <td>${formatDate(dep.date_of_birth)}</td>
                <td>${dep.gender}</td>
                <td>${dep.document_no ? escapeHtml(dep.document_no) : 'N/A'}</td>
                <td><span class="badge bg-info">${dep.relationship}</span></td>
                <td>
                    <button type="button" class="btn btn-sm btn-outline-danger" 
                            onclick="deleteDependant(${dep.id})">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    container.innerHTML = html;
}

// Delete dependant
function deleteDependant(id) {
    if (confirm('Are you sure you want to delete this dependant?')) {
        $.ajax({
            url: '<?= APP_URL ?>/migrants/delete-dependant',
            type: 'POST',
            data: {
                id: id,
                csrf_token: '<?= $_SESSION['csrf_token'] ?? '' ?>'
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    alert('Dependant deleted successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (response.error || 'Unknown error'));
                }
            },
            error: function(xhr) {
                console.error('Error:', xhr);
                alert('Error deleting dependant. Please check the console for details.');
            }
        });
    }
}

// Helper function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Helper function to format date
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB');
}
</script>

<style>
.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 25px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: linear-gradient(to bottom, 
        rgba(0,103,71,0.1) 0%,
        rgba(0,103,71,0.5) 50%,
        rgba(0,103,71,0.1) 100%);
}

.timeline-item {
    position: relative;
}

.timeline-item:last-child .timeline-content {
    margin-bottom: 0;
}

.timeline-icon {
    position: relative;
    z-index: 1;
}

.timeline-icon .rounded-circle {
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.timeline-content {
    background: white;
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 20px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.timeline-content:hover {
    transform: translateX(5px);
    box-shadow: 0 5px 15px rgba(0,103,71,0.1);
}

@media (max-width: 768px) {
    .timeline {
        padding-left: 20px;
    }
    
    .timeline-icon .rounded-circle {
        width: 40px !important;
        height: 40px !important;
        padding: 10px !important;
    }
}
</style>