<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Housekeeping Task - 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/tasks/
$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/tasks/ -> /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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_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, $new_values) {
        // 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 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');
}

// Define TASK_TYPES if not defined
if (!defined('TASK_TYPES')) {
    $task_types_array = [
        'cleaning' => 'Room Cleaning',
        'maintenance' => 'Maintenance',
        'inspection' => 'Room Inspection',
        'supply' => 'Supply Restock',
        'deep_clean' => 'Deep Cleaning',
        'other' => 'Other'
    ];
    define('TASK_TYPES', serialize($task_types_array));
}

// Define PRIORITIES if not defined
if (!defined('PRIORITIES')) {
    $priorities_array = [
        'low' => 'Low',
        'medium' => 'Medium',
        'high' => 'High',
        'urgent' => 'Urgent'
    ];
    define('PRIORITIES', serialize($priorities_array));
}

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

// Set page title
$page_title = 'Create Housekeeping Task';

// 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 task types
$task_types = [];
if (defined('TASK_TYPES')) {
    $task_types = @unserialize(TASK_TYPES) ?: [];
}
if (empty($task_types)) {
    $task_types = [
        'cleaning' => 'Room Cleaning',
        'maintenance' => 'Maintenance',
        'inspection' => 'Room Inspection',
        'supply' => 'Supply Restock',
        'deep_clean' => 'Deep Cleaning',
        'other' => 'Other'
    ];
}

// Get priorities
$priorities = [];
if (defined('PRIORITIES')) {
    $priorities = @unserialize(PRIORITIES) ?: [];
}
if (empty($priorities)) {
    $priorities = [
        'low' => 'Low',
        'medium' => 'Medium',
        'high' => 'High',
        'urgent' => 'Urgent'
    ];
}

// Handle form submission
$errors = [];
$form_data = [
    'room_id' => isset($_GET['room_id']) ? (int)$_GET['room_id'] : 0,
    'task_type' => '',
    'priority' => 'medium',
    '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'] = isset($_POST['room_id']) ? (int)$_POST['room_id'] : 0;
        $form_data['task_type'] = isset($_POST['task_type']) ? sanitize_input($_POST['task_type']) : '';
        $form_data['priority'] = isset($_POST['priority']) ? sanitize_input($_POST['priority']) : 'medium';
        $form_data['notes'] = isset($_POST['notes']) ? sanitize_input($_POST['notes']) : '';
        
        $assign_now = isset($_POST['assign_now']);
        $assign_to = $assign_now && isset($_POST['assign_to']) ? (int)$_POST['assign_to'] : null;
        
        if (!$form_data['room_id']) {
            $errors[] = 'Please select a room';
        }
        
        if (empty($form_data['task_type'])) {
            $errors[] = 'Please select a task type';
        }
        
        if ($assign_now && !$assign_to) {
            $errors[] = 'Please select a staff member to assign to';
        }
        
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                // Generate task code
                $task_code = 'HK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                
                $task_data = [
                    'task_code' => $task_code,
                    'room_id' => $form_data['room_id'],
                    'task_type' => $form_data['task_type'],
                    'priority' => $form_data['priority'],
                    'status' => $assign_now ? 'assigned' : 'pending',
                    'notes' => $form_data['notes'] ?: null,
                    'created_by' => $user_id,
                    'created_at' => date(DATETIME_FORMAT)
                ];
                
                if ($assign_now && $assign_to) {
                    $task_data['assigned_to'] = $assign_to;
                    $task_data['assigned_by'] = $user_id;
                    $task_data['assigned_at'] = date(DATETIME_FORMAT);
                }
                
                $task_id = null;
                if (function_exists('db_insert')) {
                    $task_id = db_insert('hk_tasks', $task_data);
                }
                
                // Update room housekeeping status if needed
                if ($form_data['task_type'] == 'cleaning' && function_exists('db_update')) {
                    db_update('rooms', [
                        'housekeeping_status' => 'dirty',
                        'updated_at' => date(DATETIME_FORMAT)
                    ], 'room_id = ?', [$form_data['room_id']]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, AUDIT_CREATE, 'hk_tasks', $task_id, null, $form_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Housekeeping task created successfully');
                }
                
                if (function_exists('redirect')) {
                    if ($assign_now) {
                        redirect('assign.php?task_id=' . $task_id);
                    } else {
                        redirect('index.php');
                    }
                } else {
                    if ($assign_now) {
                        header('Location: assign.php?task_id=' . $task_id);
                    } else {
                        header('Location: index.php');
                    }
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to create task: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Task creation failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Get staff for assignment dropdown
$staff = [];
if (function_exists('db_fetch_all')) {
    try {
        $staff = db_fetch_all("
            SELECT user_id, first_name, last_name 
            FROM users 
            WHERE role_id IN (7, 8) AND is_active = 1
            ORDER BY first_name
        ") ?: [];
    } catch (Exception $e) {
        error_log("Error fetching staff: " . $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>Create Housekeeping Task</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; }
            .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 Housekeeping Task</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 Housekeeping Task</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="index.php">Tasks</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; ?>

                <!-- 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 Housekeeping Task
                        </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="form-group mb-3">
                                <label for="room_id">Room <span class="text-danger">*</span></label>
                                <select class="form-select select2" id="room_id" name="room_id" required>
                                    <option value="">Select Room</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' : ''; ?>
                                                data-status="<?php echo $room['housekeeping_status'] ?? 'clean'; ?>">
                                            Room <?php echo htmlspecialchars($room['room_number'] ?? ''); ?> - 
                                            <?php echo htmlspecialchars($room['type_name'] ?? ''); ?> 
                                            (Current: <?php echo ucfirst($room['housekeeping_status'] ?? 'clean'); ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="task_type">Task Type <span class="text-danger">*</span></label>
                                        <select class="form-select" id="task_type" name="task_type" required>
                                            <option value="">Select Task Type</option>
                                            <?php foreach ($task_types as $value => $label): ?>
                                                <option value="<?php echo $value; ?>" <?php echo $form_data['task_type'] == $value ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($label); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label for="priority">Priority</label>
                                        <select class="form-select" id="priority" name="priority">
                                            <?php foreach ($priorities as $value => $label): ?>
                                                <option value="<?php echo $value; ?>" <?php echo $form_data['priority'] == $value ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($label); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo htmlspecialchars($form_data['notes']); ?></textarea>
                            </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">
                                            <label class="form-check-label" for="assign_now">
                                                Assign this task now
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div id="assign_fields" style="display: none;">
                                        <div class="form-group mb-3">
                                            <label for="assign_to">Assign To</label>
                                            <select class="form-select" id="assign_to" name="assign_to">
                                                <option value="">Select Staff Member</option>
                                                <?php foreach ($staff as $member): ?>
                                                    <option value="<?php echo $member['user_id'] ?? 0; ?>">
                                                        <?php echo escape_html(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? '')); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i> Create Task
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </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();
        } else {
            $('#assign_fields').slideUp();
        }
    });
    
    // Show current room status when room selected
    $('#room_id').on('change', function() {
        const selected = $(this).find(':selected');
        const status = selected.data('status');
        
        if (status) {
            $('#room_status_info').remove();
            $(this).after(`<small id="room_status_info" class="text-muted d-block mt-1">Current housekeeping status: <span class="badge bg-info">${status}</span></small>`);
        }
    });
    
    // Auto-set priority based on room status or guest type
    $('#room_id, #task_type').on('change', function() {
        const taskType = $('#task_type').val();
        const roomSelected = $('#room_id').find(':selected');
        
        // If it's a VIP room or checkout, set higher priority
        if (taskType === 'cleaning' && roomSelected.text().toLowerCase().includes('vip')) {
            $('#priority').val('high');
        }
    });
    
    // Trigger initial room status display if room is pre-selected
    if ($('#room_id').val()) {
        $('#room_id').trigger('change');
    }
});
</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>';
}
?>