<?php
// init.php ko shaamil karein
require_once 'init.php';

// Suraksha jaanch
if (!userHasRole(['SMM', 'Admin', 'Manager'])) {
    header("Location: my_tasks.php");
    exit();
}
$smm_user_id = $_SESSION['user_id'];

// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['mark_as_completed'])) {
    $task_id = $_POST['task_id'];
    
    $stmt = $conn->prepare("UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE id = ? AND assigned_user_id = ?");
    $stmt->bind_param("ii", $task_id, $smm_user_id);
    
    if ($stmt->execute()) {
        $_SESSION['message'] = "Task marked as completed successfully!";
        $_SESSION['message_type'] = 'success';
    } else {
        $_SESSION['message'] = "Error: " . $stmt->error;
        $_SESSION['message_type'] = 'error';
    }
    $stmt->close();
    
    header("Location: smm_workspace.php");
    exit();
}

// --- फिल्टर्स ---
$client_filter_id = $_GET['client_id'] ?? 'all';
$start_date_filter = $_GET['start_date'] ?? '';
$end_date_filter = $_GET['end_date'] ?? '';
$status_filter = $_GET['status_filter'] ?? 'active';

// --- DATA FETCHING ---
$params = [$smm_user_id];
$param_types = 'i';

if ($status_filter == 'active') {
    $sql = "SELECT t.*, c.name as client_name FROM tasks t JOIN clients c ON t.client_id = c.id WHERE t.assigned_user_id = ? AND t.is_checklist_task = TRUE AND t.status IN ('Not Started', 'Rejected')";
} else {
    $status_to_fetch = ($status_filter == 'pending') ? 'Final Review' : 'Completed';
    $sql = "SELECT t.*, c.name as client_name FROM tasks t JOIN clients c ON t.client_id = c.id WHERE t.assigned_user_id = ? AND t.is_checklist_task = TRUE AND t.status = ?";
    $params[] = $status_to_fetch;
    $param_types .= 's';
}


if ($client_filter_id != 'all' && is_numeric($client_filter_id)) {
    $sql .= " AND t.client_id = ?";
    $params[] = $client_filter_id;
    $param_types .= 'i';
}
if (!empty($start_date_filter)) {
    $sql .= " AND t.assigned_date >= ?";
    $params[] = $start_date_filter;
    $param_types .= 's';
}
if (!empty($end_date_filter)) {
    $sql .= " AND t.assigned_date <= ?";
    $params[] = $end_date_filter;
    $param_types .= 's';
}
$sql .= " ORDER BY t.created_at ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$tasks = [];
while ($row = $result->fetch_assoc()) {
    $checklist_stmt = $conn->prepare("SELECT * FROM smm_checklists WHERE task_id = ? ORDER BY FIELD(item_description, 'Shared in client group', 'Posted on Insta/FB', 'Profile Review', 'Google Review & Update')");
    $checklist_stmt->bind_param("i", $row['id']);
    $checklist_stmt->execute();
    $row['checklist'] = $checklist_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $checklist_stmt->close();
    $tasks[] = $row;
}
$stmt->close();

$clients_result = $conn->query("SELECT id, name FROM clients WHERE is_active = TRUE ORDER BY name ASC");
$all_clients = $clients_result->fetch_all(MYSQLI_ASSOC);

$conn->close();

require_once 'header.php';
?>

<title>SMM Workspace - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">SMM Workspace</h2>

<main class="p-6 md:p-10">
    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded-lg <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <div class="bg-white p-4 rounded-lg shadow-md mb-8">
        <form method="GET" action="smm_workspace.php">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div>
                    <label class="text-sm font-medium text-gray-700">Client</label>
                    <select name="client_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All Clients</option>
                        <?php foreach($all_clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>" <?php if($client_filter_id == $client['id']) echo 'selected'; ?>><?php echo htmlspecialchars($client['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">Start Date</label>
                    <input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">End Date</label>
                    <input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">Task Status</label>
                    <select name="status_filter" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="active" <?php if($status_filter == 'active') echo 'selected'; ?>>Tasks to Do</option>
                        <option value="pending" <?php if($status_filter == 'pending') echo 'selected'; ?>>Pending Review</option>
                        <option value="completed" <?php if($status_filter == 'completed') echo 'selected'; ?>>Completed</option>
                    </select>
                </div>
                <div class="flex items-center gap-4">
                    <button type="submit" class="w-full px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    <a href="smm_workspace.php" class="w-full text-center px-6 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300">Reset</a>
                </div>
            </div>
        </form>
    </div>

    <div class="bg-white rounded-lg shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Task Details</th>
                        <th class="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase" colspan="4">Checklist Items</th>
                        <th class="px-4 py-3 text-center text-xs font-semibold text-gray-600 uppercase">Action/Status</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($tasks)): ?>
                        <tr><td colspan="6" class="px-6 py-10 text-center text-gray-500">No tasks found for the selected criteria.</td></tr>
                    <?php else: ?>
                        <?php foreach ($tasks as $task): 
                            $assigned_time = new DateTime($task['created_at']);
                            $current_time = new DateTime();
                            $interval = $current_time->getTimestamp() - $assigned_time->getTimestamp();
                            $hours_passed = $interval / 3600;
                            $highlight_class = ($hours_passed > 4 && $task['status'] == 'Not Started') ? 'border-l-4 border-red-500' : '';
                        ?>
                            <tr class="<?php echo $highlight_class; ?>" x-data="{ items: <?php echo htmlspecialchars(json_encode($task['checklist'])); ?>, get allChecked() { return this.items.every(item => item.is_completed == 1) } }">
                                <td class="px-4 py-4">
                                    <p class="text-sm font-semibold text-gray-900"><?php echo htmlspecialchars($task['title']); ?></p>
                                    <p class="text-xs text-gray-500">Client: <?php echo htmlspecialchars($task['client_name']); ?> | Date: <?php echo date("d M, Y", strtotime($task['assigned_date'])); ?></p>
                                    <?php if ($task['status'] == 'Rejected'): ?><p class="text-xs text-red-600 mt-1"><strong>Rework Reason:</strong> <?php echo htmlspecialchars($task['rejection_reason']); ?></p><?php endif; ?>
                                </td>
                                <template x-for="item in items" :key="item.id">
                                    <td class="px-4 py-4 text-center">
                                        <input type="checkbox" class="h-5 w-5 rounded border-gray-300 text-blue-600" :checked="item.is_completed == 1" @change="updateChecklistItem(item.id, $event.target.checked); item.is_completed = $event.target.checked ? 1 : 0;">
                                        <label class="text-xs text-gray-500 block mt-1" x-text="item.item_description"></label>
                                    </td>
                                </template>
                                <td class="px-4 py-4 text-center">
                                    <?php if ($task['status'] == 'Completed'): ?>
                                        <span class="px-3 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Completed</span>
                                    <?php elseif ($task['status'] == 'Final Review'): ?>
                                        <span class="px-3 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">Pending Review</span>
                                    <?php else: ?>
                                        <form method="POST" action="smm_workspace.php">
                                            <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                            <button type="submit" name="mark_as_completed" :disabled="!allChecked" class="px-3 py-1 text-xs font-semibold rounded-full shadow-sm" :class="allChecked ? 'bg-green-600 text-white hover:bg-green-700' : 'bg-gray-200 text-gray-500 cursor-not-allowed'">Mark as Completed</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<script>
function updateChecklistItem(itemId, isChecked) {
    fetch('update_checklist.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_id: itemId, is_completed: isChecked })
    })
    .then(response => response.json())
    .then(data => {
        if(data.status !== 'success'){
            alert('Error updating checklist. Please refresh the page.');
        }
    });
}
</script>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>