<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Complete 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 = 'Complete Task';

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

// Get task ID from URL
$task_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$task_id) {
    set_flash_message('danger', 'Invalid task ID');
    redirect('index.php');
}

// Get task data
$task = db_fetch_one("
    SELECT t.*, r.room_number, rt.type_name
    FROM hk_tasks t
    JOIN rooms r ON t.room_id = r.room_id
    JOIN room_types rt ON r.room_type_id = rt.room_type_id
    WHERE t.task_id = ?
", [$task_id]);

if (!$task) {
    set_flash_message('danger', 'Task not found');
    redirect('index.php');
}

// Check if task can be completed
if ($task['status'] == 'completed') {
    set_flash_message('warning', 'Task is already completed');
    redirect('index.php');
}

if ($task['status'] == 'cancelled') {
    set_flash_message('danger', 'Cannot complete a cancelled task');
    redirect('index.php');
}

// Check if user is assigned or has permission
if ($task['assigned_to'] != $current_user['user_id'] && !has_permission('hk.tasks.manage_all')) {
    set_flash_message('danger', 'You are not assigned to this task');
    redirect('index.php');
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $completion_notes = sanitize_input($_POST['completion_notes'] ?? '');
        $update_room_status = isset($_POST['update_room_status']);
        $new_room_status = sanitize_input($_POST['new_room_status'] ?? 'clean');
        
        try {
            begin_transaction();
            
            // Update task
            db_update('hk_tasks', [
                'status' => 'completed',
                'completed_by' => $current_user['user_id'],
                'completed_at' => date(DATETIME_FORMAT),
                'notes' => $completion_notes ?: $task['notes']
            ], 'task_id = ?', [$task_id]);
            
            // Update room housekeeping status if requested
            if ($update_room_status) {
                db_update('rooms', [
                    'housekeeping_status' => $new_room_status
                ], 'room_id = ?', [$task['room_id']]);
            }
            
            // Create notification for task creator
            if ($task['created_by'] != $current_user['user_id']) {
                create_notification(
                    $task['created_by'],
                    NOTIFICATION_SUCCESS,
                    'Task Completed',
                    "Task for Room {$task['room_number']} has been completed",
                    'tasks/index.php'
                );
            }
            
            // Audit log
            audit_log($current_user['user_id'], AUDIT_COMPLETE, 'hk_tasks', $task_id, 
                     ['status' => $task['status']], 
                     ['status' => 'completed', 'notes' => $completion_notes]);
            
            commit_transaction();
            
            set_flash_message('success', 'Task completed successfully');
            redirect('index.php');
            
        } catch (Exception $e) {
            rollback_transaction();
            $errors[] = 'Failed to complete task: ' . $e->getMessage();
            log_message("Task completion failed: " . $e->getMessage(), 'ERROR');
        }
    }
}

// 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">Complete 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">Complete</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 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; ?>

        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Task Summary -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            Task Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered">
                            <tr>
                                <th style="width: 150px;">Task Code:</th>
                                <td><strong><?php echo $task['task_code']; ?></strong></td>
                            </tr>
                            <tr>
                                <th>Room:</th>
                                <td>
                                    Room <?php echo $task['room_number']; ?> (<?php echo $task['type_name']; ?>)
                                </td>
                            </tr>
                            <tr>
                                <th>Task Type:</th>
                                <td>
                                    <?php 
                                    $task_types = unserialize(TASK_TYPES);
                                    echo $task_types[$task['task_type']] ?? ucfirst($task['task_type']);
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Priority:</th>
                                <td>
                                    <span class="badge badge-<?php 
                                        echo $task['priority'] == 'urgent' ? 'danger' : 
                                            ($task['priority'] == 'high' ? 'warning' : 
                                            ($task['priority'] == 'medium' ? 'info' : 'secondary'));
                                    ?>">
                                        <?php echo ucfirst($task['priority']); ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Current Status:</th>
                                <td>
                                    <span class="badge badge-<?php 
                                        echo $task['status'] == 'in_progress' ? 'primary' : 
                                            ($task['status'] == 'assigned' ? 'info' : 'warning');
                                    ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $task['status'])); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php if ($task['notes']): ?>
                            <tr>
                                <th>Task Notes:</th>
                                <td><?php echo nl2br(escape_html($task['notes'])); ?></td>
                            </tr>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>

                <!-- Completion Form -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-check-circle mr-1"></i>
                            Complete Task
                        </h3>
                    </div>
                    
                    <form method="POST" id="completeForm">
                        <?php echo csrf_field(); ?>
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="completion_notes">Completion Notes (Optional)</label>
                                <textarea class="form-control" id="completion_notes" name="completion_notes" rows="3" 
                                          placeholder="Any notes about the task completion..."></textarea>
                            </div>
                            
                            <div class="card card-outline card-warning mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Update Room Status</h3>
                                </div>
                                <div class="card-body">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="update_room_status" name="update_room_status" checked>
                                            <label class="custom-control-label" for="update_room_status">
                                                Update room housekeeping status
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div id="room_status_fields">
                                        <div class="form-group">
                                            <label for="new_room_status">New Room Status</label>
                                            <select class="form-control" id="new_room_status" name="new_room_status">
                                                <option value="clean">Clean</option>
                                                <option value="inspected">Inspected</option>
                                                <option value="out_of_service">Out of Service</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Note:</strong> Completing this task will mark it as done. 
                                The room status will be updated if you choose to do so.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-check-circle mr-1"></i> Complete Task
                            </button>
                            <a href="index.php" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Quick Actions -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bolt mr-1"></i>
                            Quick Actions
                        </h3>
                    </div>
                    <div class="card-body">
                        <a href="create.php?room_id=<?php echo $task['room_id']; ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus-circle"></i> Create Another Task for this Room
                        </a>
                        <a href="../cleaning/room-status.php?room_id=<?php echo $task['room_id']; ?>" class="btn btn-sm btn-info">
                            <i class="fas fa-door-open"></i> View Room Status
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Toggle room status fields
    $('#update_room_status').on('change', function() {
        if ($(this).is(':checked')) {
            $('#room_status_fields').slideDown();
        } else {
            $('#room_status_fields').slideUp();
        }
    });
});

// Form validation
$('#completeForm').on('submit', function(e) {
    return confirm('Mark this task as completed?');
});
</script>

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