<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Update Maintenance Ticket - FIXED DATABASE STRUCTURE
 * 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 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 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 begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// 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 log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define create_notification function if it doesn't exist
if (!function_exists('create_notification')) {
    function create_notification($user_id, $type, $title, $message, $link = null) {
        if (function_exists('db_insert')) {
            try {
                db_insert('notifications', [
                    'user_id' => $user_id,
                    'type' => $type,
                    'title' => $title,
                    'message' => $message,
                    'link' => $link,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            } catch (Exception $e) {
                error_log("Failed to create notification: " . $e->getMessage());
            }
        }
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}
if (!defined('AUDIT_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}
if (!defined('NOTIFICATION_INFO')) {
    define('NOTIFICATION_INFO', 'info');
}
if (!defined('NOTIFICATION_SUCCESS')) {
    define('NOTIFICATION_SUCCESS', 'success');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

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

// Set page title
$page_title = 'Update Maintenance Ticket';

// 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 ticket ID from URL
$ticket_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$ticket_id && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    // If no ID and not POST, show selection form
    show_selection_form($base_path, $current_user, $user_id);
    exit;
}

// Get ticket data
$ticket = null;
if ($ticket_id && function_exists('db_fetch_one')) {
    try {
        $ticket = db_fetch_one("
            SELECT t.*, r.room_number
            FROM maintenance_tickets t
            LEFT JOIN rooms r ON t.room_id = r.room_id
            WHERE t.ticket_id = ?
        ", [$ticket_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching ticket: " . $e->getMessage());
    }
}

// Get maintenance staff
$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());
    }
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        $ticket_id = isset($_POST['ticket_id']) ? (int)$_POST['ticket_id'] : 0;
        
        if (!$ticket_id) {
            $errors[] = 'Invalid ticket ID';
        } else {
            // Get ticket data
            $ticket = null;
            if (function_exists('db_fetch_one')) {
                try {
                    $ticket = db_fetch_one("SELECT * FROM maintenance_tickets WHERE ticket_id = ?", [$ticket_id]) ?: [];
                } catch (Exception $e) {
                    error_log("Error fetching ticket for update: " . $e->getMessage());
                }
            }
            
            if (empty($ticket)) {
                $errors[] = 'Ticket not found';
            } else {
                try {
                    if (function_exists('begin_transaction')) {
                        begin_transaction();
                    }
                    
                    $update_data = [];
                    $message = '';
                    
                    switch ($action) {
                        case 'assign':
                            $assigned_to = isset($_POST['assigned_to']) ? (int)$_POST['assigned_to'] : 0;
                            $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
                            
                            if (!$assigned_to) {
                                $errors[] = 'Please select a staff member';
                            } else {
                                $update_data = [
                                    'assigned_to' => $assigned_to,
                                    'status' => 'assigned',
                                    'notes' => $notes ?: ($ticket['notes'] ?? ''),
                                    'updated_at' => date(DATETIME_FORMAT)
                                ];
                                
                                // Create notification
                                if (function_exists('create_notification')) {
                                    create_notification(
                                        $assigned_to,
                                        NOTIFICATION_INFO,
                                        'Maintenance Ticket Assigned',
                                        "Ticket #{$ticket['ticket_code']} has been assigned to you",
                                        'view.php?id=' . $ticket_id
                                    );
                                }
                                
                                $message = 'Ticket assigned successfully';
                            }
                            break;
                            
                        case 'start':
                            $update_data = [
                                'status' => 'in_progress',
                                'updated_at' => date(DATETIME_FORMAT)
                            ];
                            $message = 'Work started on ticket';
                            break;
                            
                        case 'resolve':
                            $resolution_notes = isset($_POST['resolution_notes']) ? sanitize_input($_POST['resolution_notes']) : '';
                            $actual_cost = !empty($_POST['actual_cost']) ? (float)$_POST['actual_cost'] : null;
                            
                            $update_data = [
                                'status' => 'resolved',
                                'resolution_notes' => $resolution_notes,
                                'actual_cost' => $actual_cost,
                                'resolved_by' => $user_id,
                                'resolved_at' => date(DATETIME_FORMAT),
                                'updated_at' => date(DATETIME_FORMAT)
                            ];
                            
                            // Update room status if it was marked for maintenance
                            if (!empty($ticket['room_id']) && function_exists('db_update')) {
                                db_update('rooms', [
                                    'status' => 'available'
                                ], 'room_id = ?', [$ticket['room_id']]);
                            }
                            
                            // Create notification for reporter
                            if (!empty($ticket['reported_by']) && function_exists('create_notification')) {
                                create_notification(
                                    $ticket['reported_by'],
                                    NOTIFICATION_SUCCESS,
                                    'Maintenance Resolved',
                                    "Ticket #{$ticket['ticket_code']} has been resolved",
                                    'view.php?id=' . $ticket_id
                                );
                            }
                            
                            $message = 'Ticket resolved successfully';
                            break;
                            
                        case 'close':
                            $update_data = [
                                'status' => 'closed',
                                'updated_at' => date(DATETIME_FORMAT)
                            ];
                            $message = 'Ticket closed';
                            break;
                            
                        case 'update':
                            $priority = isset($_POST['priority']) ? sanitize_input($_POST['priority']) : '';
                            $estimated_cost = !empty($_POST['estimated_cost']) ? (float)$_POST['estimated_cost'] : null;
                            $notes = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
                            
                            if ($priority) $update_data['priority'] = $priority;
                            if ($estimated_cost !== null) $update_data['estimated_cost'] = $estimated_cost;
                            if ($notes) $update_data['notes'] = $notes;
                            $update_data['updated_at'] = date(DATETIME_FORMAT);
                            
                            $message = 'Ticket updated successfully';
                            break;
                    }
                    
                    if (empty($errors) && !empty($update_data)) {
                        if (function_exists('db_update')) {
                            db_update('maintenance_tickets', $update_data, 'ticket_id = ?', [$ticket_id]);
                        }
                        
                        // Audit log
                        if (function_exists('audit_log')) {
                            audit_log($user_id, AUDIT_UPDATE, 'maintenance_tickets', $ticket_id, 
                                     $ticket, $update_data);
                        }
                        
                        if (function_exists('commit_transaction')) {
                            commit_transaction();
                        }
                        
                        if (function_exists('set_flash_message')) {
                            set_flash_message('success', $message);
                        }
                        
                        if (function_exists('redirect')) {
                            redirect('view.php?id=' . $ticket_id);
                        } else {
                            header('Location: view.php?id=' . $ticket_id);
                            exit;
                        }
                    } else if (empty($errors)) {
                        $errors[] = 'No changes to update';
                    } else {
                        if (function_exists('rollback_transaction')) {
                            rollback_transaction();
                        }
                    }
                    
                } catch (Exception $e) {
                    if (function_exists('rollback_transaction')) {
                        rollback_transaction();
                    }
                    $errors[] = 'Failed to update ticket: ' . $e->getMessage();
                    if (function_exists('log_message')) {
                        log_message("Ticket update failed: " . $e->getMessage(), 'ERROR');
                    }
                }
            }
        }
    }
}

// If we have errors or no ticket, show form
if (!empty($errors) || empty($ticket)) {
    show_selection_form($base_path, $current_user, $user_id);
    exit;
}

// 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>Update Maintenance Ticket</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; }
            .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; }
            .text-end { text-align: right; }
        </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="#">Update Maintenance Ticket</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">Update Ticket: <?php echo htmlspecialchars($ticket['ticket_code'] ?? 'N/A'); ?></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"><a href="tickets.php">Maintenance</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $ticket_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Update</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Error Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mt-2 mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-4">
                <!-- Ticket Summary -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Ticket Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Ticket #:</th>
                                <td><strong><?php echo htmlspecialchars($ticket['ticket_code'] ?? 'N/A'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Room:</th>
                                <td>
                                    <?php if (!empty($ticket['room_id'])): ?>
                                        Room <?php echo htmlspecialchars($ticket['room_number'] ?? ''); ?>
                                    <?php else: ?>
                                        Common Area
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Issue Type:</th>
                                <td><?php echo escape_html($ticket['issue_type'] ?? ''); ?></td>
                            </tr>
                            <tr>
                                <th>Priority:</th>
                                <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>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <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>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-md-8">
                <!-- Action Forms based on current status -->
                <?php if (($ticket['status'] ?? '') == 'open'): ?>
                    <!-- Open Ticket Actions -->
                    <div class="card card-warning">
                        <div class="card-header">
                            <h3 class="card-title">Open Ticket Actions</h3>
                        </div>
                        <div class="card-body">
                            <form method="POST" class="mb-3">
                                <?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" value="<?php echo $ticket_id; ?>">
                                
                                <div class="form-group mb-3">
                                    <label for="assigned_to">Assign Ticket</label>
                                    <select class="form-select" id="assigned_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="notes">Assignment Notes</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">Assign Ticket</button>
                            </form>
                            
                            <hr>
                            
                            <form method="POST" class="mb-3">
                                <?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="update">
                                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                
                                <h5>Update Ticket Details</h5>
                                
                                <div class="form-group mb-3">
                                    <label for="priority">Priority</label>
                                    <select class="form-select" id="priority" name="priority">
                                        <option value="">No Change</option>
                                        <option value="low">Low</option>
                                        <option value="medium">Medium</option>
                                        <option value="high">High</option>
                                        <option value="urgent">Urgent</option>
                                    </select>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="estimated_cost">Estimated Cost</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                        <input type="number" class="form-control" id="estimated_cost" name="estimated_cost" 
                                               value="<?php echo escape_html($ticket['estimated_cost'] ?? ''); ?>" step="0.01" min="0">
                                    </div>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="notes">Additional Notes</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="2"><?php echo escape_html($ticket['notes'] ?? ''); ?></textarea>
                                </div>
                                
                                <button type="submit" class="btn btn-warning">Update Details</button>
                            </form>
                        </div>
                    </div>
                    
                <?php elseif (($ticket['status'] ?? '') == 'assigned' || ($ticket['status'] ?? '') == 'in_progress'): ?>
                    <!-- Assigned/In Progress Actions -->
                    <div class="card card-success">
                        <div class="card-header">
                            <h3 class="card-title">Work Progress</h3>
                        </div>
                        <div class="card-body">
                            <form method="POST" class="mb-3">
                                <?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="start">
                                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                
                                <?php if (($ticket['status'] ?? '') == 'assigned'): ?>
                                    <button type="submit" class="btn btn-primary btn-lg w-100">
                                        <i class="fas fa-play"></i> Start Work
                                    </button>
                                <?php endif; ?>
                            </form>
                            
                            <form 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="resolve">
                                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                
                                <h5>Resolve Ticket</h5>
                                
                                <div class="form-group mb-3">
                                    <label for="resolution_notes">Resolution Notes</label>
                                    <textarea class="form-control" id="resolution_notes" name="resolution_notes" rows="3" required></textarea>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="actual_cost">Actual Cost</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo CURRENCY_SYMBOL; ?></span>
                                        <input type="number" class="form-control" id="actual_cost" name="actual_cost" 
                                               step="0.01" min="0">
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn btn-success">Mark as Resolved</button>
                            </form>
                        </div>
                    </div>
                    
                <?php elseif (($ticket['status'] ?? '') == 'resolved'): ?>
                    <!-- Resolved Actions -->
                    <div class="card card-info">
                        <div class="card-header">
                            <h3 class="card-title">Resolved Ticket</h3>
                        </div>
                        <div class="card-body">
                            <p>This ticket has been resolved. You can close it or reopen if needed.</p>
                            
                            <form method="POST" class="d-inline">
                                <?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="close">
                                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                <button type="submit" class="btn btn-secondary" onclick="return confirm('Close this ticket?')">
                                    <i class="fas fa-check-circle"></i> Close Ticket
                                </button>
                            </form>
                            
                            <form method="POST" class="d-inline ms-2">
                                <?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="start">
                                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                                <button type="submit" class="btn btn-warning" onclick="return confirm('Reopen this ticket?')">
                                    <i class="fas fa-undo"></i> Reopen
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

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

/**
 * Show ticket selection form
 */
function show_selection_form($base_path, $current_user, $user_id) {
    // Get open tickets for selection
    $open_tickets = [];
    if (function_exists('db_fetch_all')) {
        try {
            $open_tickets = db_fetch_all("
                SELECT t.*, r.room_number
                FROM maintenance_tickets t
                LEFT JOIN rooms r ON t.room_id = r.room_id
                WHERE t.status NOT IN ('resolved', 'closed')
                ORDER BY 
                    CASE t.priority 
                        WHEN 'urgent' THEN 1
                        WHEN 'high' THEN 2
                        WHEN 'medium' THEN 3
                        WHEN 'low' THEN 4
                    END,
                    t.created_at
            ") ?: [];
        } catch (Exception $e) {
            error_log("Error fetching open tickets: " . $e->getMessage());
        }
    }
    
    // Include header
    $header_path = $base_path . '/views/partials/header.php';
    if (file_exists($header_path)) {
        require_once $header_path;
    } else {
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Update Maintenance Ticket</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; }
                .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="#">Update Maintenance Ticket</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">Update Maintenance Ticket</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"><a href="tickets.php">Maintenance</a></li>
                        <li class="breadcrumb-item active">Update</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-6 offset-md-3">
                    <div class="card card-info">
                        <div class="card-header">
                            <h3 class="card-title">Select Ticket to Update</h3>
                        </div>
                        <div class="card-body">
                            <?php if (empty($open_tickets)): ?>
                                <p class="text-center text-muted">No open tickets available for update</p>
                                <div class="text-center">
                                    <a href="create.php" class="btn btn-primary">Create New Ticket</a>
                                </div>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach ($open_tickets as $ticket): ?>
                                        <a href="?id=<?php echo $ticket['ticket_id'] ?? 0; ?>" class="list-group-item list-group-item-action">
                                            <div class="d-flex justify-content-between">
                                                <div>
                                                    <strong><?php echo htmlspecialchars($ticket['ticket_code'] ?? ''); ?></strong>
                                                    <br>
                                                    <small>
                                                        <?php echo !empty($ticket['room_id']) ? "Room " . htmlspecialchars($ticket['room_number'] ?? '') : 'Common Area'; ?> - 
                                                        <?php echo escape_html($ticket['issue_type'] ?? ''); ?>
                                                    </small>
                                                </div>
                                                <div class="text-end">
                                                    <span class="badge bg-<?php 
                                                        $priority = $ticket['priority'] ?? '';
                                                        echo $priority == 'urgent' ? 'danger' : 
                                                            ($priority == 'high' ? 'warning' : 
                                                            ($priority == 'medium' ? 'info' : 'secondary'));
                                                    ?>">
                                                        <?php echo ucfirst($priority); ?>
                                                    </span>
                                                    <br>
                                                    <small class="text-muted"><?php echo ucfirst(str_replace('_', ' ', $ticket['status'] ?? '')); ?></small>
                                                </div>
                                            </div>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <?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>';
    }
    exit;
}
?>