<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Maintenance Tickets 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/housekeeping/maintenance/
$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/housekeeping/maintenance/ -> /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 format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, H:i') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define display_flash_messages function if it doesn't exist
if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && is_array($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $msg) {
                $type = $msg['type'] ?? 'info';
                $message = $msg['message'] ?? '';
                echo "<div class='alert alert-{$type} alert-dismissible fade show'>";
                echo escape_html($message);
                echo "<button type='button' class='btn-close' data-bs-dismiss='alert'></button>";
                echo "</div>";
            }
            unset($_SESSION['flash_messages']);
        }
    }
}

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

// Check permission
if (function_exists('require_permission')) {
    require_permission('hk.maintenance.view');
}

// Set page title
$page_title = 'Maintenance Tickets';

// 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 filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$priority = isset($_GET['priority']) ? trim($_GET['priority']) : '';
$assigned_to = isset($_GET['assigned_to']) && $_GET['assigned_to'] !== '' ? (int)$_GET['assigned_to'] : null;
$room_id = isset($_GET['room_id']) && $_GET['room_id'] !== '' ? (int)$_GET['room_id'] : null;
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (t.ticket_code LIKE ? OR t.description LIKE ? OR r.room_number LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term]);
}

if (!empty($status)) {
    $where .= " AND t.status = ?";
    $params[] = $status;
}

if (!empty($priority)) {
    $where .= " AND t.priority = ?";
    $params[] = $priority;
}

if ($assigned_to) {
    $where .= " AND t.assigned_to = ?";
    $params[] = $assigned_to;
}

if ($room_id) {
    $where .= " AND t.room_id = ?";
    $params[] = $room_id;
}

if (!empty($date_from)) {
    $where .= " AND DATE(t.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where .= " AND DATE(t.created_at) <= ?";
    $params[] = $date_to;
}

// Get maintenance tickets
$tickets = [];
if (function_exists('db_fetch_all')) {
    try {
        $tickets = db_fetch_all("
            SELECT 
                t.*,
                r.room_number,
                u.first_name as reported_first, u.last_name as reported_last,
                a.first_name as assigned_first, a.last_name as assigned_last,
                res.first_name as resolved_first, res.last_name as resolved_last
            FROM maintenance_tickets t
            LEFT JOIN rooms r ON t.room_id = r.room_id
            LEFT JOIN users u ON t.reported_by = u.user_id
            LEFT JOIN users a ON t.assigned_to = a.user_id
            LEFT JOIN users res ON t.resolved_by = res.user_id
            WHERE $where
            ORDER BY 
                CASE t.priority 
                    WHEN 'urgent' THEN 1
                    WHEN 'high' THEN 2
                    WHEN 'medium' THEN 3
                    WHEN 'low' THEN 4
                END,
                CASE t.status
                    WHEN 'open' THEN 1
                    WHEN 'assigned' THEN 2
                    WHEN 'in_progress' THEN 3
                    WHEN 'resolved' THEN 4
                    WHEN 'closed' THEN 5
                END,
                t.created_at DESC
        ", $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching tickets: " . $e->getMessage());
    }
}

// Get maintenance staff for filter
$maintenance_staff = [];
if (function_exists('db_fetch_all')) {
    try {
        $maintenance_staff = db_fetch_all("
            SELECT user_id, first_name, last_name 
            FROM users 
            WHERE role_id = 9 AND is_active = 1
            ORDER BY first_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching maintenance staff: " . $e->getMessage());
    }
}

// Get rooms for filter
$rooms = [];
if (function_exists('db_fetch_all')) {
    try {
        $rooms = db_fetch_all("
            SELECT room_id, room_number 
            FROM rooms 
            WHERE is_active = 1 
            ORDER BY room_number
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching rooms: " . $e->getMessage());
    }
}

// Get statistics
$stats = [
    'open' => 0,
    'assigned' => 0,
    'in_progress' => 0,
    'resolved' => 0,
    'urgent' => 0,
    'overdue' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['open'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status = 'open'") ?: 0;
        $stats['assigned'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status = 'assigned'") ?: 0;
        $stats['in_progress'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status = 'in_progress'") ?: 0;
        $stats['resolved'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status = 'resolved'") ?: 0;
        $stats['urgent'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE priority = 'urgent' AND status NOT IN ('resolved', 'closed')") ?: 0;
        $stats['overdue'] = db_fetch_value("SELECT COUNT(*) FROM maintenance_tickets WHERE status NOT IN ('resolved', 'closed') AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching stats: " . $e->getMessage());
    }
}

// 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>Maintenance Tickets</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; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-primary { background-color: #007bff !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-success { background-color: #28a745 !important; }
            .bg-danger { background-color: #dc3545 !important; }
            .bg-secondary { background-color: #6c757d !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; }
            .mb-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
        </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="#">Maintenance Tickets</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">Maintenance Tickets</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/housekeeping/dashboard.php">Housekeeping</a></li>
                    <li class="breadcrumb-item active">Maintenance</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php display_flash_messages(); ?>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['open']; ?></h3>
                        <p>Open</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-folder-open"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo $stats['assigned']; ?></h3>
                        <p>Assigned</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-check"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['in_progress']; ?></h3>
                        <p>In Progress</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-spinner"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['resolved']; ?></h3>
                        <p>Resolved</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['urgent']; ?></h3>
                        <p>Urgent</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo $stats['overdue']; ?></h3>
                        <p>Overdue (7+ days)</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-body">
                        <a href="create.php" class="btn btn-primary me-2">
                            <i class="fas fa-plus-circle"></i> New Ticket
                        </a>
                        <a href="update.php" class="btn btn-info me-2">
                            <i class="fas fa-edit"></i> Update Status
                        </a>
                        <button type="button" class="btn btn-warning me-2" onclick="exportTickets()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="search" placeholder="Search tickets..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <option value="open" <?php echo $status == 'open' ? 'selected' : ''; ?>>Open</option>
                            <option value="assigned" <?php echo $status == 'assigned' ? 'selected' : ''; ?>>Assigned</option>
                            <option value="in_progress" <?php echo $status == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                            <option value="resolved" <?php echo $status == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                            <option value="closed" <?php echo $status == 'closed' ? 'selected' : ''; ?>>Closed</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="priority">
                            <option value="">All Priorities</option>
                            <option value="low" <?php echo $priority == 'low' ? 'selected' : ''; ?>>Low</option>
                            <option value="medium" <?php echo $priority == 'medium' ? 'selected' : ''; ?>>Medium</option>
                            <option value="high" <?php echo $priority == 'high' ? 'selected' : ''; ?>>High</option>
                            <option value="urgent" <?php echo $priority == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="assigned_to">
                            <option value="">All Staff</option>
                            <?php foreach ($maintenance_staff as $staff): ?>
                                <option value="<?php echo $staff['user_id'] ?? 0; ?>" <?php echo $assigned_to == ($staff['user_id'] ?? 0) ? 'selected' : ''; ?>>
                                    <?php echo escape_html(($staff['first_name'] ?? '') . ' ' . ($staff['last_name'] ?? '')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="room_id">
                            <option value="">All Rooms</option>
                            <?php foreach ($rooms as $room): ?>
                                <option value="<?php echo $room['room_id'] ?? 0; ?>" <?php echo $room_id == ($room['room_id'] ?? 0) ? 'selected' : ''; ?>>
                                    Room <?php echo escape_html($room['room_number'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_from" placeholder="From" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_to" placeholder="To" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i> Apply
                        </button>
                    </div>
                    
                    <div class="col-md-2">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times"></i> Clear
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Tickets Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-tools me-1"></i>
                    Maintenance Tickets (<?php echo count($tickets); ?>)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($tickets)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-tools fa-4x mb-3"></i>
                        <h5>No maintenance tickets found</h5>
                        <p>Create a new ticket or adjust your filters</p>
                        <a href="create.php" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i> New Ticket
                        </a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Ticket #</th>
                                    <th>Room</th>
                                    <th>Issue Type</th>
                                    <th>Priority</th>
                                    <th>Status</th>
                                    <th>Reported By</th>
                                    <th>Assigned To</th>
                                    <th>Created</th>
                                    <th>Age</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($tickets as $ticket): 
                                    $age = isset($ticket['created_at']) ? (time() - strtotime($ticket['created_at'])) / 86400 : 0;
                                ?>
                                <tr class="<?php 
                                    $priority = $ticket['priority'] ?? '';
                                    $status = $ticket['status'] ?? '';
                                    echo $priority == 'urgent' ? 'table-danger' : 
                                        ($priority == 'high' ? 'table-warning' : '');
                                    echo ($age > 7 && $status != 'resolved' && $status != 'closed') ? ' table-secondary' : '';
                                ?>">
                                    <td>
                                        <a href="view.php?id=<?php echo $ticket['ticket_id'] ?? 0; ?>">
                                            <strong><?php echo htmlspecialchars($ticket['ticket_code'] ?? ''); ?></strong>
                                        </a>
                                    </td>
                                    <td>
                                        <?php if (!empty($ticket['room_id'])): ?>
                                            <a href="/HMSPOS/rooms/rooms/view.php?id=<?php echo $ticket['room_id']; ?>">
                                                Room <?php echo htmlspecialchars($ticket['room_number'] ?? ''); ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted">Common Area</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo escape_html($ticket['issue_type'] ?? ''); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            $priority = $ticket['priority'] ?? '';
                                            echo $priority == 'urgent' ? 'danger' : 
                                                ($priority == 'high' ? 'warning' : 
                                                ($priority == 'medium' ? 'info' : 'secondary'));
                                        ?>">
                                            <?php echo ucfirst($priority); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            $status = $ticket['status'] ?? '';
                                            echo $status == 'resolved' ? 'success' : 
                                                ($status == 'closed' ? 'secondary' : 
                                                ($status == 'in_progress' ? 'primary' : 
                                                ($status == 'assigned' ? 'info' : 'warning')));
                                        ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php echo escape_html(($ticket['reported_first'] ?? '') . ' ' . ($ticket['reported_last'] ?? '')); ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($ticket['assigned_to'])): ?>
                                            <?php echo escape_html(($ticket['assigned_first'] ?? '') . ' ' . ($ticket['assigned_last'] ?? '')); ?>
                                        <?php else: ?>
                                            <span class="text-muted">Unassigned</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php echo isset($ticket['created_at']) ? date('M d, H:i', strtotime($ticket['created_at'])) : 'N/A'; ?>
                                    </td>
                                    <td>
                                        <?php if ($age < 1): ?>
                                            <span class="badge bg-success">Today</span>
                                        <?php elseif ($age < 2): ?>
                                            <span class="badge bg-info">Yesterday</span>
                                        <?php else: ?>
                                            <span class="badge bg-<?php echo $age > 7 ? 'danger' : 'warning'; ?>">
                                                <?php echo round($age); ?> days
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $ticket['ticket_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (($ticket['status'] ?? '') != 'resolved' && ($ticket['status'] ?? '') != 'closed'): ?>
                                                <a href="update.php?id=<?php echo $ticket['ticket_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Update">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if (empty($ticket['assigned_to']) && ($ticket['status'] ?? '') == 'open'): ?>
                                                <button type="button" class="btn btn-sm btn-success" 
                                                        onclick="assignTicket(<?php echo $ticket['ticket_id'] ?? 0; ?>)"
                                                        title="Assign">
                                                    <i class="fas fa-user-plus"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Assign Ticket Modal -->
<div class="modal fade" id="assignModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">Assign Ticket</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="update.php" method="POST">
                <?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="assign">
                <input type="hidden" name="ticket_id" id="assign_ticket_id">
                
                <div class="modal-body">
                    <div class="form-group mb-3">
                        <label for="assign_to">Assign To</label>
                        <select class="form-select" id="assign_to" name="assigned_to" required>
                            <option value="">Select Staff Member</option>
                            <?php foreach ($maintenance_staff as $staff): ?>
                                <option value="<?php echo $staff['user_id'] ?? 0; ?>">
                                    <?php echo escape_html(($staff['first_name'] ?? '') . ' ' . ($staff['last_name'] ?? '')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="assign_notes">Notes</label>
                        <textarea class="form-control" id="assign_notes" name="notes" rows="2"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Assign</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function assignTicket(ticketId) {
    $('#assign_ticket_id').val(ticketId);
    
    // Initialize Bootstrap 5 modal
    const assignModal = new bootstrap.Modal(document.getElementById('assignModal'));
    assignModal.show();
}

function exportTickets() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = 'export.php?' + params.toString();
}
</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>';
}
?>