<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Documents Management - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/guests/documents/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/guests/documents/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define format_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return '';
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        return date('M d, Y', $time);
    }
}

// Define format_bytes function if it doesn't exist
if (!function_exists('format_bytes')) {
    function format_bytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        
        $bytes /= pow(1024, $pow);
        
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}

// Define get_file_extension function if it doesn't exist
if (!function_exists('get_file_extension')) {
    function get_file_extension($filename) {
        return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    }
}

// Define uploads_url function if it doesn't exist
if (!function_exists('uploads_url')) {
    function uploads_url($path = '') {
        return '/HMSPOS/uploads/' . ltrim($path, '/');
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define upload_file function if it doesn't exist
if (!function_exists('upload_file')) {
    function upload_file($file, $target_dir, $allowed_types) {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'errors' => ['File upload error']];
        }
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowed_types)) {
            return ['success' => false, 'errors' => ['File type not allowed']];
        }
        
        // Check file size (default 5MB)
        $max_size = defined('UPLOAD_MAX_SIZE') ? UPLOAD_MAX_SIZE : 5 * 1024 * 1024;
        if ($file['size'] > $max_size) {
            return ['success' => false, 'errors' => ['File size exceeds maximum allowed']];
        }
        
        $new_filename = uniqid() . '_' . time() . '.' . $extension;
        $target_path = rtrim($target_dir, '/') . '/' . $new_filename;
        
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }
        
        if (move_uploaded_file($file['tmp_name'], $target_path)) {
            return ['success' => true, 'filename' => $new_filename];
        }
        
        return ['success' => false, 'errors' => ['Failed to move uploaded file']];
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('UPLOAD_PATH_IDS')) {
    define('UPLOAD_PATH_IDS', $base_path . '/uploads/ids/');
}
if (!defined('UPLOAD_MAX_SIZE')) {
    define('UPLOAD_MAX_SIZE', 5 * 1024 * 1024); // 5MB
}
if (!defined('AUDIT_UPLOAD')) {
    define('AUDIT_UPLOAD', 'upload');
}
if (!defined('AUDIT_DELETE')) {
    define('AUDIT_DELETE', 'delete');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('guests.documents');
}

// Set page title
$page_title = 'Guest Documents';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get guest ID from URL
$guest_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$guest_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid guest ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get guest data
$guest = [];
if (function_exists('db_fetch_one')) {
    try {
        $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching guest: " . $e->getMessage());
    }
}

if (empty($guest)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Guest not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Handle file upload
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'upload':
                if (isset($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
                    $document_type = isset($_POST['document_type']) ? sanitize_input($_POST['document_type']) : 'other';
                    $document_number = isset($_POST['document_number']) ? sanitize_input($_POST['document_number']) : '';
                    $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
                    
                    if (function_exists('upload_file')) {
                        $upload_result = upload_file(
                            $_FILES['document'],
                            defined('UPLOAD_PATH_IDS') ? UPLOAD_PATH_IDS : ($base_path . '/uploads/ids/'),
                            ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx']
                        );
                        
                        if ($upload_result['success'] && function_exists('db_insert')) {
                            $document_id = db_insert('guest_documents', [
                                'guest_id' => $guest_id,
                                'document_type' => $document_type,
                                'document_number' => $document_number ?: null,
                                'document_path' => $upload_result['filename'],
                                'uploaded_by' => $user_id,
                                'uploaded_at' => date('Y-m-d H:i:s')
                            ]);
                            
                            // Create activity record
                            if (function_exists('db_insert')) {
                                db_insert('guest_activity', [
                                    'guest_id' => $guest_id,
                                    'activity_type' => 'document_uploaded',
                                    'description' => "Uploaded $document_type document" . ($document_number ? " (#$document_number)" : ''),
                                    'created_by' => $user_id,
                                    'created_at' => date('Y-m-d H:i:s')
                                ]);
                            }
                            
                            // Audit log
                            if (function_exists('audit_log')) {
                                audit_log($user_id, AUDIT_UPLOAD, 'guest_documents', $document_id, null, [
                                    'guest_id' => $guest_id,
                                    'document_type' => $document_type,
                                    'filename' => $upload_result['filename']
                                ]);
                            }
                            
                            $message = 'Document uploaded successfully';
                        } else {
                            $error = 'Failed to upload document: ' . implode(', ', $upload_result['errors'] ?? ['Unknown error']);
                        }
                    } else {
                        $error = 'Upload function not available';
                    }
                } else {
                    $error = 'Please select a file to upload';
                }
                break;
                
            case 'delete':
                $document_id = isset($_POST['document_id']) ? (int)$_POST['document_id'] : 0;
                
                if ($document_id && function_exists('db_fetch_one') && function_exists('db_delete')) {
                    // Get document info
                    $document = db_fetch_one("SELECT * FROM guest_documents WHERE document_id = ? AND guest_id = ?", 
                                            [$document_id, $guest_id]);
                    
                    if ($document) {
                        // Delete file
                        $file_path = (defined('UPLOAD_PATH_IDS') ? UPLOAD_PATH_IDS : ($base_path . '/uploads/ids/')) . $document['document_path'];
                        if (file_exists($file_path)) {
                            unlink($file_path);
                        }
                        
                        // Delete from database
                        db_delete('guest_documents', 'document_id = ?', [$document_id]);
                        
                        // Create activity record
                        if (function_exists('db_insert')) {
                            db_insert('guest_activity', [
                                'guest_id' => $guest_id,
                                'activity_type' => 'document_deleted',
                                'description' => "Deleted {$document['document_type']} document",
                                'created_by' => $user_id,
                                'created_at' => date('Y-m-d H:i:s')
                            ]);
                        }
                        
                        // Audit log
                        if (function_exists('audit_log')) {
                            audit_log($user_id, AUDIT_DELETE, 'guest_documents', $document_id);
                        }
                        
                        $message = 'Document deleted successfully';
                    }
                }
                break;
        }
    }
}

// Get guest documents
$documents = [];
if (function_exists('db_fetch_all')) {
    try {
        $documents = db_fetch_all("
            SELECT d.*, u.first_name, u.last_name
            FROM guest_documents d
            LEFT JOIN users u ON d.uploaded_by = u.user_id
            WHERE d.guest_id = ?
            ORDER BY d.uploaded_at DESC
        ", [$guest_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching documents: " . $e->getMessage());
    }
}

// Document type options
$document_types = [
    'passport' => 'Passport',
    'national_id' => 'National ID',
    'drivers_license' => 'Driver\'s License',
    'visa' => 'Visa',
    'registration' => 'Registration Card',
    'invoice' => 'Invoice',
    'receipt' => 'Receipt',
    'other' => 'Other'
];

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Guest Documents</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); border-radius: 0.25rem; background: #fff; display: flex; margin-bottom: 20px; min-height: 80px; }
            .info-box-icon { border-radius: 0.25rem 0 0 0.25rem; display: flex; align-items: center; justify-content: center; width: 70px; font-size: 1.875rem; text-align: center; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-info { background-color: #17a2b8 !important; color: #fff; }
            .bg-light { background-color: #f8f9fa !important; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-3 { margin-top: 1rem; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Guest Documents</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Documents: <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/guests/dashboard.php">Guests</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Guests</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $guest_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Documents</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Upload Form -->
            <div class="col-md-4">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-upload me-1"></i>
                            Upload Document
                        </h3>
                    </div>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="upload">
                        
                        <div class="card-body">
                            <div class="form-group mb-3">
                                <label for="document_type">Document Type</label>
                                <select class="form-select" id="document_type" name="document_type" required>
                                    <option value="">Select Type</option>
                                    <?php foreach ($document_types as $value => $label): ?>
                                        <option value="<?php echo $value; ?>"><?php echo htmlspecialchars($label); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="document_number">Document Number (Optional)</label>
                                <input type="text" class="form-control" id="document_number" name="document_number">
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Notes (Optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="document">Select File</label>
                                <input type="file" class="form-control" id="document" name="document" 
                                       accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx" required>
                                <small class="text-muted">
                                    Allowed: JPG, PNG, GIF, PDF, DOC, DOCX. Max size: <?php echo function_exists('format_bytes') ? format_bytes(UPLOAD_MAX_SIZE) : '5 MB'; ?>
                                </small>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload me-1"></i> Upload Document
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Quick Stats -->
                <div class="card card-info mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Document Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-info elevation-1">
                                <i class="fas fa-file-alt"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Documents</span>
                                <span class="info-box-number"><?php echo count($documents); ?></span>
                            </div>
                        </div>
                        
                        <?php 
                        $type_counts = [];
                        foreach ($documents as $doc) {
                            $type = $doc['document_type'] ?? 'other';
                            $type_counts[$type] = ($type_counts[$type] ?? 0) + 1;
                        }
                        ?>
                        
                        <?php if (!empty($type_counts)): ?>
                            <hr>
                            <h6>By Type:</h6>
                            <?php foreach ($type_counts as $type => $count): ?>
                                <div class="d-flex justify-content-between mb-1">
                                    <span><?php echo $document_types[$type] ?? ucfirst($type); ?></span>
                                    <span class="badge bg-secondary"><?php echo $count; ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Documents List -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Guest Documents
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($documents)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-file-alt fa-4x mb-3"></i>
                                <h5>No documents uploaded</h5>
                                <p>Use the form on the left to upload documents for this guest</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Type</th>
                                            <th>Document #</th>
                                            <th>Filename</th>
                                            <th>Uploaded By</th>
                                            <th>Uploaded At</th>
                                            <th width="120">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($documents as $doc): ?>
                                        <tr>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    $doc_type = $doc['document_type'] ?? 'other';
                                                    echo $doc_type == 'passport' ? 'primary' : 
                                                        ($doc_type == 'national_id' ? 'info' : 
                                                        ($doc_type == 'drivers_license' ? 'warning' : 'secondary'));
                                                ?>">
                                                    <?php echo $document_types[$doc_type] ?? ucfirst($doc_type); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($doc['document_number'] ?? '-'); ?>
                                            </td>
                                            <td>
                                                <i class="fas fa-<?php 
                                                    $ext = !empty($doc['document_path']) ? get_file_extension($doc['document_path']) : '';
                                                    echo $ext == 'pdf' ? 'file-pdf' : ($ext ? 'file-image' : 'file');
                                                ?> me-2"></i>
                                                <?php echo htmlspecialchars($doc['document_path'] ?? ''); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars(($doc['first_name'] ?? '') . ' ' . ($doc['last_name'] ?? '')); ?>
                                            </td>
                                            <td>
                                                <?php echo isset($doc['uploaded_at']) ? date('M d, Y H:i', strtotime($doc['uploaded_at'])) : 'N/A'; ?>
                                                <br>
                                                <small class="text-muted"><?php echo function_exists('time_ago') ? time_ago($doc['uploaded_at'] ?? '') : ''; ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="<?php echo function_exists('uploads_url') ? uploads_url('ids/' . ($doc['document_path'] ?? '')) : '/HMSPOS/uploads/ids/' . ($doc['document_path'] ?? ''); ?>" 
                                                       class="btn btn-sm btn-info" target="_blank" title="View">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    
                                                    <a href="<?php echo function_exists('uploads_url') ? uploads_url('ids/' . ($doc['document_path'] ?? '')) : '/HMSPOS/uploads/ids/' . ($doc['document_path'] ?? ''); ?>" 
                                                       class="btn btn-sm btn-success" download title="Download">
                                                        <i class="fas fa-download"></i>
                                                    </a>
                                                    
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="deleteDocument(<?php echo $doc['document_id'] ?? 0; ?>)"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Delete Document</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this document?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle me-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteForm">
                    <?php if (function_exists('csrf_field')): ?>
                        <?php echo csrf_field(); ?>
                    <?php else: ?>
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                    <?php endif; ?>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="document_id" id="deleteDocumentId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // File input preview
    $('#document').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
});

function deleteDocument(documentId) {
    $('#deleteDocumentId').val(documentId);
    
    // Initialize Bootstrap 5 modal
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}
</script>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>