<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Create Housekeeping Task
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('hk.tasks.manage');

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

// Get current user
$current_user = current_user();

// Get rooms for dropdown
$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
");

// Get task types
$task_types = unserialize(TASK_TYPES);

// Get priorities
$priorities = unserialize(PRIORITIES);

// 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') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        // Get and validate input
        $form_data['room_id'] = (int)($_POST['room_id'] ?? 0);
        $form_data['task_type'] = sanitize_input($_POST['task_type'] ?? '');
        $form_data['priority'] = sanitize_input($_POST['priority'] ?? 'medium');
        $form_data['notes'] = sanitize_input($_POST['notes'] ?? '');
        
        $assign_now = isset($_POST['assign_now']);
        $assign_to = $assign_now ? (int)($_POST['assign_to'] ?? 0) : 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 {
                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' => $current_user['user_id']
                ];
                
                if ($assign_now) {
                    $task_data['assigned_to'] = $assign_to;
                    $task_data['assigned_by'] = $current_user['user_id'];
                    $task_data['assigned_at'] = date(DATETIME_FORMAT);
                }
                
                $task_id = db_insert('hk_tasks', $task_data);
                
                // Update room housekeeping status if needed
                if ($form_data['task_type'] == 'cleaning') {
                    db_update('rooms', [
                        'housekeeping_status' => 'dirty'
                    ], 'room_id = ?', [$form_data['room_id']]);
                }
                
                // Audit log
                audit_log($current_user['user_id'], AUDIT_CREATE, 'hk_tasks', $task_id, null, $form_data);
                
                commit_transaction();
                
                set_flash_message('success', 'Housekeeping task created successfully');
                
                if ($assign_now) {
                    redirect('assign.php?task_id=' . $task_id);
                } else {
                    redirect('index.php');
                }
                
            } catch (Exception $e) {
                rollback_transaction();
                $errors[] = 'Failed to create task: ' . $e->getMessage();
                log_message("Task creation failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// Get staff for assignment dropdown
$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
");

// Include header
require_once dirname(__DIR__, 3) . '/views/partials/header.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="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('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 mr-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo $error; ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="close" data-dismiss="alert">&times;</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 mr-1"></i>
                            New Housekeeping Task
                        </h3>
                    </div>
                    
                    <form method="POST" id="createForm">
                        <?php echo csrf_field(); ?>
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="room_id">Room <span class="text-danger">*</span></label>
                                <select class="form-control 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']; ?>" 
                                                <?php echo $form_data['room_id'] == $room['room_id'] ? 'selected' : ''; ?>
                                                data-status="<?php echo $room['housekeeping_status']; ?>">
                                            Room <?php echo $room['room_number']; ?> - 
                                            <?php echo $room['type_name']; ?> 
                                            (Current: <?php echo ucfirst($room['housekeeping_status']); ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="task_type">Task Type <span class="text-danger">*</span></label>
                                        <select class="form-control" 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 $label; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="priority">Priority</label>
                                        <select class="form-control" id="priority" name="priority">
                                            <?php foreach ($priorities as $value => $label): ?>
                                                <option value="<?php echo $value; ?>" <?php echo $form_data['priority'] == $value ? 'selected' : ''; ?>>
                                                    <?php echo $label; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo escape_html($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">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="assign_now" name="assign_now">
                                            <label class="custom-control-label" for="assign_now">
                                                Assign this task now
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div id="assign_fields" style="display: none;">
                                        <div class="form-group">
                                            <label for="assign_to">Assign To</label>
                                            <select class="form-control" id="assign_to" name="assign_to">
                                                <option value="">Select Staff Member</option>
                                                <?php foreach ($staff as $member): ?>
                                                    <option value="<?php echo $member['user_id']; ?>">
                                                        <?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 mr-1"></i> Create Task
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Initialize 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">Current housekeeping status: ${status}</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');
        }
    });
});
</script>

<?php
// Include footer
require_once dirname(__DIR__, 3) . '/views/partials/footer.php';
?>