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

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

// Get staff members
$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
");

// Get unassigned tasks
$unassigned_tasks = db_fetch_all("
    SELECT 
        t.*,
        r.room_number, rt.type_name,
        (SELECT COUNT(*) FROM hk_tasks WHERE assigned_to = u.user_id AND status IN ('assigned', 'in_progress')) as current_load
    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
    CROSS JOIN users u
    WHERE t.status = 'pending'
    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
");

// Get tasks assigned to current user
$my_tasks = db_fetch_all("
    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.assigned_to = ? AND t.status IN ('assigned', 'in_progress')
    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
", [$current_user['user_id']]);

// Handle bulk assignment
$errors = [];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'assign_single') {
            $task_id = (int)($_POST['task_id'] ?? 0);
            $staff_id = (int)($_POST['staff_id'] ?? 0);
            
            if ($task_id && $staff_id) {
                try {
                    begin_transaction();
                    
                    db_update('hk_tasks', [
                        'assigned_to' => $staff_id,
                        'assigned_by' => $current_user['user_id'],
                        'assigned_at' => date(DATETIME_FORMAT),
                        'status' => 'assigned'
                    ], 'task_id = ?', [$task_id]);
                    
                    // Create notification
                    create_notification(
                        $staff_id,
                        NOTIFICATION_INFO,
                        'New Task Assigned',
                        'A new housekeeping task has been assigned to you',
                        'tasks/index.php'
                    );
                    
                    audit_log($current_user['user_id'], AUDIT_ASSIGN, 'hk_tasks', $task_id);
                    
                    commit_transaction();
                    
                    $message = 'Task assigned successfully';
                    
                } catch (Exception $e) {
                    rollback_transaction();
                    $errors[] = 'Failed to assign task: ' . $e->getMessage();
                }
            }
        } elseif ($action === 'assign_multiple') {
            $task_ids = $_POST['task_ids'] ?? [];
            $staff_id = (int)($_POST['bulk_staff_id'] ?? 0);
            
            if (!empty($task_ids) && $staff_id) {
                try {
                    begin_transaction();
                    
                    $placeholders = implode(',', array_fill(0, count($task_ids), '?'));
                    $params = array_merge([$staff_id, $current_user['user_id'], date(DATETIME_FORMAT)], $task_ids);
                    
                    db_query("
                        UPDATE hk_tasks 
                        SET assigned_to = ?, 
                            assigned_by = ?, 
                            assigned_at = ?, 
                            status = 'assigned'
                        WHERE task_id IN ($placeholders)
                    ", $params);
                    
                    // Create single notification for multiple tasks
                    create_notification(
                        $staff_id,
                        NOTIFICATION_INFO,
                        'Multiple Tasks Assigned',
                        count($task_ids) . ' new tasks have been assigned to you',
                        'tasks/index.php'
                    );
                    
                    audit_log($current_user['user_id'], 'bulk_assign', 'hk_tasks', null, null, ['count' => count($task_ids)]);
                    
                    commit_transaction();
                    
                    $message = count($task_ids) . ' tasks assigned successfully';
                    
                } catch (Exception $e) {
                    rollback_transaction();
                    $errors[] = 'Failed to assign tasks: ' . $e->getMessage();
                }
            }
        }
    }
}

// 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">Assign Tasks</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">Assign</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?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; ?>

        <!-- Staff Workload -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-users mr-1"></i>
                            Staff Workload
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($staff as $member): 
                                $workload = db_fetch_value("
                                    SELECT COUNT(*) FROM hk_tasks 
                                    WHERE assigned_to = ? AND status IN ('assigned', 'in_progress')
                                ", [$member['user_id']]);
                                
                                $max_load = 8; // Maximum tasks per staff
                                $percentage = ($workload / $max_load) * 100;
                            ?>
                            <div class="col-md-3 col-sm-6 mb-3">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-<?php 
                                        echo $percentage >= 80 ? 'danger' : ($percentage >= 50 ? 'warning' : 'success');
                                    ?> elevation-1">
                                        <i class="fas fa-user"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text"><?php echo $member['first_name']; ?></span>
                                        <span class="info-box-number"><?php echo $workload; ?>/<?php echo $max_load; ?> tasks</span>
                                        <div class="progress">
                                            <div class="progress-bar bg-<?php 
                                                echo $percentage >= 80 ? 'danger' : ($percentage >= 50 ? 'warning' : 'success');
                                            ?>" style="width: <?php echo min(100, $percentage); ?>%"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Unassigned Tasks -->
            <div class="col-md-8">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock mr-1"></i>
                            Unassigned Tasks
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectAll()">
                                Select All
                            </button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="deselectAll()">
                                Deselect All
                            </button>
                        </div>
                    </div>
                    
                    <form method="POST" id="bulkAssignForm">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="assign_multiple">
                        
                        <div class="card-body p-0">
                            <?php if (empty($unassigned_tasks)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                    <p>No pending tasks to assign</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" id="selectAllCheckbox" onchange="toggleAll()">
                                                </th>
                                                <th>Task #</th>
                                                <th>Room</th>
                                                <th>Task Type</th>
                                                <th>Priority</th>
                                                <th>Created</th>
                                                <th>Notes</th>
                                                <th>Assign To</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($unassigned_tasks as $task): ?>
                                            <tr class="<?php echo $task['priority'] == 'urgent' ? 'table-danger' : ''; ?>">
                                                <td>
                                                    <input type="checkbox" name="task_ids[]" value="<?php echo $task['task_id']; ?>" 
                                                           class="task-checkbox">
                                                </td>
                                                <td>
                                                    <strong><?php echo $task['task_code']; ?></strong>
                                                </td>
                                                <td>
                                                    Room <?php echo $task['room_number']; ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo $task['type_name']; ?></small>
                                                </td>
                                                <td>
                                                    <?php 
                                                    $task_types = unserialize(TASK_TYPES);
                                                    echo $task_types[$task['task_type']] ?? ucfirst($task['task_type']);
                                                    ?>
                                                </td>
                                                <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>
                                                <td>
                                                    <?php echo format_date($task['created_at'], 'M d, H:i'); ?>
                                                </td>
                                                <td>
                                                    <?php if ($task['notes']): ?>
                                                        <span title="<?php echo escape_html($task['notes']); ?>">
                                                            <i class="fas fa-sticky-note text-muted"></i>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <select class="form-control form-control-sm single-assign" 
                                                            onchange="assignSingle(<?php echo $task['task_id']; ?>, this.value)">
                                                        <option value="">Assign to...</option>
                                                        <?php foreach ($staff as $member): ?>
                                                            <option value="<?php echo $member['user_id']; ?>">
                                                                <?php echo $member['first_name'] . ' ' . $member['last_name']; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($unassigned_tasks)): ?>
                        <div class="card-footer">
                            <div class="row">
                                <div class="col-md-6">
                                    <span id="selectedCount">0</span> task(s) selected
                                </div>
                                <div class="col-md-6">
                                    <div class="input-group">
                                        <select class="form-control form-control-sm" name="bulk_staff_id" id="bulk_staff_id">
                                            <option value="">Select Staff</option>
                                            <?php foreach ($staff as $member): ?>
                                                <option value="<?php echo $member['user_id']; ?>">
                                                    <?php echo $member['first_name'] . ' ' . $member['last_name']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-sm btn-success" onclick="return confirmBulkAssign()">
                                                Assign Selected
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <!-- My Assigned Tasks -->
            <div class="col-md-4">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-tasks mr-1"></i>
                            My Assigned Tasks
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($my_tasks)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3"></i>
                                <p>No tasks assigned to you</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($my_tasks as $task): ?>
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <strong>Room <?php echo $task['room_number']; ?></strong>
                                            <br>
                                            <small class="text-muted">
                                                <?php 
                                                $task_types = unserialize(TASK_TYPES);
                                                echo $task_types[$task['task_type']] ?? ucfirst($task['task_type']);
                                                ?>
                                            </small>
                                        </div>
                                        <div class="text-right">
                                            <span class="badge badge-<?php 
                                                echo $task['priority'] == 'urgent' ? 'danger' : 
                                                    ($task['priority'] == 'high' ? 'warning' : 'info');
                                            ?>">
                                                <?php echo ucfirst($task['priority']); ?>
                                            </span>
                                            <br>
                                            <a href="complete.php?id=<?php echo $task['task_id']; ?>" 
                                               class="btn btn-sm btn-success mt-2">
                                                <i class="fas fa-check"></i> Complete
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Single Assignment Form -->
<form id="singleAssignForm" method="POST" style="display: none;">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="action" value="assign_single">
    <input type="hidden" name="task_id" id="single_task_id">
    <input type="hidden" name="staff_id" id="single_staff_id">
</form>

<script>
let selectedTasks = new Set();

$(document).ready(function() {
    updateSelectedCount();
});

function toggleAll() {
    const checked = $('#selectAllCheckbox').prop('checked');
    $('.task-checkbox').each(function() {
        $(this).prop('checked', checked);
        const taskId = $(this).val();
        if (checked) {
            selectedTasks.add(taskId);
        } else {
            selectedTasks.delete(taskId);
        }
    });
    updateSelectedCount();
}

$('.task-checkbox').on('change', function() {
    const taskId = $(this).val();
    if ($(this).prop('checked')) {
        selectedTasks.add(taskId);
    } else {
        selectedTasks.delete(taskId);
    }
    updateSelectAll();
    updateSelectedCount();
});

function updateSelectAll() {
    const total = $('.task-checkbox').length;
    const checked = $('.task-checkbox:checked').length;
    
    if (total > 0 && checked === total) {
        $('#selectAllCheckbox').prop('checked', true).prop('indeterminate', false);
    } else if (checked > 0) {
        $('#selectAllCheckbox').prop('checked', false).prop('indeterminate', true);
    } else {
        $('#selectAllCheckbox').prop('checked', false).prop('indeterminate', false);
    }
}

function updateSelectedCount() {
    $('#selectedCount').text(selectedTasks.size);
}

function selectAll() {
    $('.task-checkbox').prop('checked', true).each(function() {
        selectedTasks.add($(this).val());
    });
    $('#selectAllCheckbox').prop('checked', true);
    updateSelectedCount();
}

function deselectAll() {
    $('.task-checkbox').prop('checked', false);
    selectedTasks.clear();
    $('#selectAllCheckbox').prop('checked', false);
    updateSelectedCount();
}

function assignSingle(taskId, staffId) {
    if (!staffId) return;
    
    if (confirm('Assign this task to the selected staff member?')) {
        $('#single_task_id').val(taskId);
        $('#single_staff_id').val(staffId);
        $('#singleAssignForm').submit();
    }
}

function confirmBulkAssign() {
    const selected = selectedTasks.size;
    const staffId = $('#bulk_staff_id').val();
    
    if (selected === 0) {
        alert('Please select at least one task');
        return false;
    }
    
    if (!staffId) {
        alert('Please select a staff member');
        return false;
    }
    
    return confirm(`Assign ${selected} task(s) to the selected staff member?`);
}
</script>

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