<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Maintenance Ticket - FIXED PATH & VALIDATION
 * 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_CREATE')) {
    define('AUDIT_CREATE', 'create');
}
if (!defined('NOTIFICATION_INFO')) {
    define('NOTIFICATION_INFO', 'info');
}
if (!defined('NOTIFICATION_WARNING')) {
    define('NOTIFICATION_WARNING', 'warning');
}
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 = 'Create 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 rooms for dropdown
$rooms = [];
if (function_exists('db_fetch_all')) {
    try {
        $rooms = db_fetch_all("
            SELECT r.*, rt.type_name 
            FROM rooms r
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            WHERE r.is_active = 1
            ORDER BY r.room_number
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching rooms: " . $e->getMessage());
    }
}

// Get maintenance staff for assignment
$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
        ") ?: [];
        
        // Debug log - remove in production
        if (empty($maintenance_staff)) {
            error_log("WARNING: No maintenance staff found with role_id = 9");
        }
    } catch (Exception $e) {
        error_log("Error fetching maintenance staff: " . $e->getMessage());
    }
}

// Handle form submission
$errors = [];
$form_data = [
    'room_id' => isset($_GET['room_id']) ? (int)$_GET['room_id'] : 0,
    'issue_type' => '',
    'description' => '',
    'priority' => 'medium',
    'assigned_to' => '',
    'estimated_cost' => '',
    'notes' => ''
];

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 {
        // Get and validate input
        $form_data['room_id'] = !empty($_POST['room_id']) ? (int)$_POST['room_id'] : null;
        $form_data['issue_type'] = isset($_POST['issue_type']) ? sanitize_input($_POST['issue_type']) : '';
        $form_data['description'] = isset($_POST['description']) ? sanitize_input($_POST['description']) : '';
        $form_data['priority'] = isset($_POST['priority']) ? sanitize_input($_POST['priority']) : 'medium';
        $form_data['assigned_to'] = !empty($_POST['assigned_to']) ? (int)$_POST['assigned_to'] : null;
        $form_data['estimated_cost'] = !empty($_POST['estimated_cost']) ? (float)$_POST['estimated_cost'] : null;
        $form_data['notes'] = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        $assign_now = isset($_POST['assign_now']) && $_POST['assign_now'] == 'on';
        
        // Validate required fields
        if (empty($form_data['issue_type'])) {
            $errors[] = 'Issue type is required';
        }
        
        if (empty($form_data['description'])) {
            $errors[] = 'Description is required';
        }
        
        if ($assign_now && empty($form_data['assigned_to'])) {
            $errors[] = 'Please select a staff member to assign to';
        }
        
        if (!empty($form_data['estimated_cost']) && $form_data['estimated_cost'] < 0) {
            $errors[] = 'Estimated cost cannot be negative';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate ticket code
                $ticket_code = 'MT-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                $ticket_data = [
                    'ticket_code' => $ticket_code,
                    'room_id' => $form_data['room_id'],
                    'reported_by' => $user_id,
                    'issue_type' => $form_data['issue_type'],
                    'description' => $form_data['description'],
                    'priority' => $form_data['priority'],
                    'status' => $assign_now ? 'assigned' : 'open',
                    'estimated_cost' => $form_data['estimated_cost'],
                    'notes' => $form_data['notes'] ?: null,
                    'created_at' => date(DATETIME_FORMAT)
                ];
                
                if ($assign_now && $form_data['assigned_to']) {
                    $ticket_data['assigned_to'] = $form_data['assigned_to'];
                }
                
                $ticket_id = null;
                if (function_exists('db_insert')) {
                    $ticket_id = db_insert('maintenance_tickets', $ticket_data);
                }
                
                // Update room status if maintenance is critical
                if ($form_data['priority'] == 'urgent' && $form_data['room_id'] && function_exists('db_update') && function_exists('db_fetch_one')) {
                    db_update('rooms', [
                        'status' => 'maintenance'
                    ], 'room_id = ?', [$form_data['room_id']]);
                    
                    // Get room number
                    $room = db_fetch_one("SELECT room_number FROM rooms WHERE room_id = ?", [$form_data['room_id']]);
                    
                    // Create notification for front desk
                    if (function_exists('create_notification')) {
                        create_notification(
                            null, // Send to all front desk? In production, you'd have a proper notification system
                            NOTIFICATION_WARNING,
                            'Urgent Maintenance',
                            "Room " . ($room['room_number'] ?? 'Unknown') . " has been marked for urgent maintenance",
                            'maintenance/view.php?id=' . $ticket_id
                        );
                    }
                }
                
                // Create notification for assigned staff
                if ($assign_now && $form_data['assigned_to'] && function_exists('create_notification')) {
                    create_notification(
                        $form_data['assigned_to'],
                        NOTIFICATION_INFO,
                        'New Maintenance Ticket',
                        "You have been assigned ticket #$ticket_code",
                        'maintenance/view.php?id=' . $ticket_id
                    );
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_CREATE, 'maintenance_tickets', $ticket_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Maintenance ticket created successfully');
                }
                
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $ticket_id);
                } else {
                    header('Location: view.php?id=' . $ticket_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create ticket: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Ticket creation failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// 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>Create Maintenance Ticket</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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; }
            .mt-3 { margin-top: 1rem; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Create 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">Create 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">Create</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- 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; ?>

                <!-- Warning if no maintenance staff -->
                <?php if (empty($maintenance_staff)): ?>
                    <div class="alert alert-warning alert-dismissible fade show">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Warning:</strong> No maintenance staff members found in the system. Please add maintenance staff (role_id = 9) before assigning tickets.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Create Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-plus-circle me-1"></i>
                            New Maintenance Ticket
                        </h3>
                    </div>
                    
                    <form method="POST" id="createForm">
                        <?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; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="room_id">Room (Optional)</label>
                                        <select class="form-select select2" id="room_id" name="room_id">
                                            <option value="">Common Area / Not Room Specific</option>
                                            <?php foreach ($rooms as $room): ?>
                                                <option value="<?php echo $room['room_id'] ?? 0; ?>" 
                                                        <?php echo $form_data['room_id'] == ($room['room_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    Room <?php echo escape_html($room['room_number'] ?? ''); ?> - <?php echo escape_html($room['type_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="issue_type">Issue Type <span class="text-danger">*</span></label>
                                        <select class="form-select" id="issue_type" name="issue_type" required>
                                            <option value="">Select Issue Type</option>
                                            <option value="Plumbing" <?php echo ($form_data['issue_type'] ?? '') == 'Plumbing' ? 'selected' : ''; ?>>Plumbing</option>
                                            <option value="Electrical" <?php echo ($form_data['issue_type'] ?? '') == 'Electrical' ? 'selected' : ''; ?>>Electrical</option>
                                            <option value="HVAC" <?php echo ($form_data['issue_type'] ?? '') == 'HVAC' ? 'selected' : ''; ?>>HVAC</option>
                                            <option value="Furniture" <?php echo ($form_data['issue_type'] ?? '') == 'Furniture' ? 'selected' : ''; ?>>Furniture</option>
                                            <option value="Electronics" <?php echo ($form_data['issue_type'] ?? '') == 'Electronics' ? 'selected' : ''; ?>>Electronics (TV, etc.)</option>
                                            <option value="Structural" <?php echo ($form_data['issue_type'] ?? '') == 'Structural' ? 'selected' : ''; ?>>Structural</option>
                                            <option value="Security" <?php echo ($form_data['issue_type'] ?? '') == 'Security' ? 'selected' : ''; ?>>Security</option>
                                            <option value="Other" <?php echo ($form_data['issue_type'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="description">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="description" name="description" rows="3" required><?php echo escape_html($form_data['description'] ?? ''); ?></textarea>
                                <small class="text-muted">Provide detailed description of the issue</small>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="priority">Priority</label>
                                        <select class="form-select" id="priority" name="priority">
                                            <option value="low" <?php echo ($form_data['priority'] ?? '') == 'low' ? 'selected' : ''; ?>>Low</option>
                                            <option value="medium" <?php echo ($form_data['priority'] ?? '') == 'medium' ? 'selected' : ''; ?>>Medium</option>
                                            <option value="high" <?php echo ($form_data['priority'] ?? '') == 'high' ? 'selected' : ''; ?>>High</option>
                                            <option value="urgent" <?php echo ($form_data['priority'] ?? '') == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <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($form_data['estimated_cost'] ?? ''); ?>" step="0.01" min="0">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="notes">Additional Notes</label>
                                        <input type="text" class="form-control" id="notes" name="notes" 
                                               value="<?php echo escape_html($form_data['notes'] ?? ''); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card card-outline card-info mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Assignment Options</h3>
                                </div>
                                <div class="card-body">
                                    <div class="form-group mb-3">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="assign_now" name="assign_now" 
                                                   <?php echo (!empty($maintenance_staff)) ? '' : 'disabled'; ?>>
                                            <label class="form-check-label" for="assign_now">
                                                Assign this ticket now
                                            </label>
                                        </div>
                                        <?php if (empty($maintenance_staff)): ?>
                                            <small class="text-danger">Cannot assign - no maintenance staff available</small>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div id="assign_fields" style="display: none;">
                                        <div class="form-group mb-3">
                                            <label for="assigned_to">Assign To</label>
                                            <select class="form-select" id="assigned_to" name="assigned_to">
                                                <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>
                                </div>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Note:</strong> Urgent tickets will automatically mark the room as under maintenance.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary" <?php echo empty($maintenance_staff) ? 'disabled' : ''; ?>>
                                <i class="fas fa-save me-1"></i> Create Ticket
                            </button>
                            <a href="tickets.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Quick Tips -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-lightbulb me-1"></i>
                            Tips for Effective Tickets
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Be specific about the location of the issue
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Include any error messages or unusual sounds
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Note if the issue affects guest comfort
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                For urgent issues, call maintenance directly
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                Take photos if possible (use the upload feature)
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });
    }
    
    // Toggle assign fields
    $('#assign_now').on('change', function() {
        if ($(this).is(':checked')) {
            $('#assign_fields').slideDown();
            $('#assigned_to').prop('required', true);
        } else {
            $('#assign_fields').slideUp();
            $('#assigned_to').prop('required', false);
        }
    });
    
    // Warn if urgent priority selected
    $('#priority').on('change', function() {
        if ($(this).val() === 'urgent') {
            if (!confirm('Setting priority to urgent may mark the room as under maintenance. Continue?')) {
                $(this).val('high');
            }
        }
    });
    
    // Debug: Log form submission for troubleshooting
    $('#createForm').on('submit', function(e) {
        console.log('Form submitting...');
        console.log('Assign Now checked:', $('#assign_now').is(':checked'));
        console.log('Assigned To value:', $('#assigned_to').val());
    });
});

// Form validation
$('#createForm').on('submit', function(e) {
    const issueType = $('#issue_type').val();
    const description = $('#description').val();
    const assignNow = $('#assign_now').is(':checked');
    const assignedTo = $('#assigned_to').val();
    
    console.log('Validation - Assign Now:', assignNow);
    console.log('Validation - Assigned To:', assignedTo);
    
    if (!issueType) {
        e.preventDefault();
        alert('Please select an issue type');
        return false;
    }
    
    if (!description || !description.trim()) {
        e.preventDefault();
        alert('Please provide a description');
        return false;
    }
    
    if (assignNow && (!assignedTo || assignedTo === '')) {
        e.preventDefault();
        alert('Please select a staff member to assign to');
        return false;
    }
    
    return true;
});
</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>';
}
?>