<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Documents Management - FIXED VERSION
 * 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
// Current file: /HMSPOS/guests/guests/documents.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$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/guests/guests/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// 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';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.php';
}

// Require authentication
require_auth();

// 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 helper functions if they don't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        if (is_array($data)) {
            return array_map('sanitize_input', $data);
        }
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

if (!function_exists('format_datetime')) {
    function format_datetime($datetime) {
        if (empty($datetime)) return '';
        return date('d/m/Y H:i', strtotime($datetime));
    }
}

if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return $diff . ' seconds ago';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } else {
            return date('M d, Y', $time);
        }
    }
}

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

if (!function_exists('format_bytes')) {
    function format_bytes($bytes) {
        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        } else {
            return $bytes . ' bytes';
        }
    }
}

if (!function_exists('get_file_extension')) {
    function get_file_extension($filename) {
        return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    }
}

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,
            'time' => time()
        ];
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        if (strpos($url, 'http') === 0) {
            header('Location: ' . $url);
        } else {
            header('Location: /HMSPOS/guests/guests/' . ltrim($url, '/'));
        }
        exit;
    }
}

if (!function_exists('upload_file')) {
    function upload_file($file, $upload_dir, $allowed_types) {
        $result = ['success' => false, 'filename' => '', 'errors' => []];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $result['errors'][] = 'File upload error: ' . $file['error'];
            return $result;
        }
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowed_types)) {
            $result['errors'][] = 'Invalid file type. Allowed: ' . implode(', ', $allowed_types);
            return $result;
        }
        
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $destination = rtrim($upload_dir, '/') . '/' . $filename;
        
        // Ensure directory exists
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            $result['success'] = true;
            $result['filename'] = $filename;
        } else {
            $result['errors'][] = 'Failed to move uploaded file';
        }
        
        return $result;
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_UPLOAD')) define('AUDIT_UPLOAD', 'upload');
if (!defined('AUDIT_DELETE')) define('AUDIT_DELETE', 'delete');

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('guests.documents');
// }

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

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

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

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

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

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

// Define upload path
$upload_path = $base_path . '/uploads/ids/';
if (!file_exists($upload_path)) {
    mkdir($upload_path, 0777, true);
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $error = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'upload':
                if (isset($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
                    $document_type = $_POST['document_type'] ?? 'other';
                    $document_number = $_POST['document_number'] ?? '';
                    $notes = $_POST['notes'] ?? '';
                    
                    $upload_result = upload_file(
                        $_FILES['document'],
                        $upload_path,
                        ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx']
                    );
                    
                    if ($upload_result['success']) {
                        try {
                            $document_data = [
                                'guest_id' => $guest_id,
                                'document_type' => $document_type,
                                'document_number' => $document_number ?: null,
                                'document_path' => $upload_result['filename'],
                                'notes' => $notes ?: null,
                                'uploaded_by' => $user_id,
                                'uploaded_at' => date('Y-m-d H:i:s')
                            ];
                            
                            if (function_exists('db_insert')) {
                                $document_id = db_insert('guest_documents', $document_data);
                            } else {
                                // Fallback direct insert
                                $pdo = get_db_connection();
                                $sql = "INSERT INTO guest_documents (guest_id, document_type, document_number, document_path, notes, uploaded_by, uploaded_at) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?)";
                                $stmt = $pdo->prepare($sql);
                                $stmt->execute([
                                    $guest_id,
                                    $document_type,
                                    $document_number ?: null,
                                    $upload_result['filename'],
                                    $notes ?: null,
                                    $user_id,
                                    date('Y-m-d H:i:s')
                                ]);
                                $document_id = $pdo->lastInsertId();
                            }
                            
                            // Create activity record (if table exists)
                            try {
                                $activity_data = [
                                    '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')
                                ];
                                
                                if (function_exists('db_insert')) {
                                    db_insert('guest_activity', $activity_data);
                                }
                            } catch (Exception $e) {
                                error_log("Error creating activity record: " . $e->getMessage());
                            }
                            
                            // Audit log
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'upload', 'guest_documents', $document_id, null, [
                                    'guest_id' => $guest_id,
                                    'document_type' => $document_type,
                                    'filename' => $upload_result['filename']
                                ]);
                            }
                            
                            $message = 'Document uploaded successfully';
                            
                        } catch (Exception $e) {
                            $error = 'Failed to save document: ' . $e->getMessage();
                            error_log("Document upload error: " . $e->getMessage());
                        }
                    } else {
                        $error = 'Failed to upload document: ' . implode(', ', $upload_result['errors']);
                    }
                } else {
                    $error = 'Please select a file to upload';
                }
                break;
                
            case 'delete':
                $document_id = (int)($_POST['document_id'] ?? 0);
                
                if ($document_id) {
                    try {
                        // 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 = $upload_path . $document['document_path'];
                            if (file_exists($file_path)) {
                                unlink($file_path);
                            }
                            
                            // Delete from database
                            if (function_exists('db_delete')) {
                                db_delete('guest_documents', 'document_id = ?', [$document_id]);
                            } else {
                                $pdo = get_db_connection();
                                $pdo->prepare("DELETE FROM guest_documents WHERE document_id = ?")->execute([$document_id]);
                            }
                            
                            // Create activity record (if table exists)
                            try {
                                $activity_data = [
                                    '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')
                                ];
                                
                                if (function_exists('db_insert')) {
                                    db_insert('guest_activity', $activity_data);
                                }
                            } catch (Exception $e) {
                                error_log("Error creating activity record: " . $e->getMessage());
                            }
                            
                            // Audit log
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'delete', 'guest_documents', $document_id);
                            }
                            
                            $message = 'Document deleted successfully';
                        }
                    } catch (Exception $e) {
                        $error = 'Failed to delete document: ' . $e->getMessage();
                        error_log("Document delete error: " . $e->getMessage());
                    }
                }
                break;
        }
    }
}

// Get guest documents
$documents = [];
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; }
        </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 (!empty($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 (!empty($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 bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="upload">
                        
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="document_type" class="form-label">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 $label; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="document_number" class="form-label">Document Number (Optional)</label>
                                <input type="text" class="form-control" id="document_number" name="document_number">
                            </div>
                            
                            <div class="mb-3">
                                <label for="notes" class="form-label">Notes (Optional)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="document" class="form-label">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(defined('UPLOAD_MAX_SIZE') ? UPLOAD_MAX_SIZE : 5242880) : '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">
                                <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 
                                                    echo ($doc['document_type'] ?? '') == 'passport' ? 'primary' : 
                                                        (($doc['document_type'] ?? '') == 'national_id' ? 'info' : 
                                                        (($doc['document_type'] ?? '') == 'drivers_license' ? 'warning' : 'secondary'));
                                                ?>">
                                                    <?php echo $document_types[$doc['document_type'] ?? 'other'] ?? ucfirst($doc['document_type'] ?? 'other'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo !empty($doc['document_number']) ? escape_html($doc['document_number']) : '-'; ?>
                                            </td>
                                            <td>
                                                <i class="fas fa-<?php 
                                                    $ext = pathinfo($doc['document_path'] ?? '', PATHINFO_EXTENSION);
                                                    echo $ext == 'pdf' ? 'file-pdf' : (in_array($ext, ['jpg', 'jpeg', 'png', 'gif']) ? 'file-image' : 'file');
                                                ?> me-2"></i>
                                                <?php echo escape_html(basename($doc['document_path'] ?? '')); ?>
                                            </td>
                                            <td>
                                                <?php echo escape_html(($doc['first_name'] ?? '') . ' ' . ($doc['last_name'] ?? '')); ?>
                                            </td>
                                            <td>
                                                <?php echo !empty($doc['uploaded_at']) ? format_datetime($doc['uploaded_at']) : ''; ?>
                                                <br>
                                                <small class="text-muted"><?php echo !empty($doc['uploaded_at']) ? time_ago($doc['uploaded_at']) : ''; ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="/HMSPOS/uploads/ids/<?php echo urlencode($doc['document_path'] ?? ''); ?>" 
                                                       class="btn btn-sm btn-info" target="_blank" title="View">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    
                                                    <a href="/HMSPOS/uploads/ids/<?php echo urlencode($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">
                <h5 class="modal-title">Delete Document</h5>
                <button type="button" class="btn-close" 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 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() {
        // Show file name (optional)
    });
});

function deleteDocument(documentId) {
    document.getElementById('deleteDocumentId').value = documentId;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}
</script>

<style>
.info-box {
    min-height: 70px;
    margin-bottom: 10px;
}
.info-box .info-box-icon {
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 1.5rem;
}
.info-box .info-box-content {
    margin-left: 60px;
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-3 { margin-top: 1rem; }
.badge.bg-primary { background-color: #007bff; color: #fff; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</style>

<?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>';
}
?>