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

// Suraksha jaanch
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$is_admin_or_manager = userHasRole(['Admin', 'Manager']);

// Session se message aur highlight ID prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
$highlight_task_id = $_SESSION['highlight_task_id'] ?? 0;
unset($_SESSION['message'], $_SESSION['message_type'], $_SESSION['highlight_task_id']);

// --- UPDATE TASK LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($is_admin_or_manager) {
        if (isset($_POST['update_task'])) {
            $task_id_to_update = $_POST['task_id'];
            $new_user_id = $_POST['assigned_user_id'];
            $new_smm_id = $_POST['smm_user_id'];
            $new_work_type = $_POST['work_type'];
            $new_description = $_POST['description'] ?? null;
            $new_assigned_date = $_POST['assigned_date'] ?? null;

            $update_sql = "UPDATE tasks SET assigned_user_id = ?, smm_user_id = ?, work_type = ?, description = ?";
            $update_params = [$new_user_id, $new_smm_id, $new_work_type, $new_description];
            $update_types = "iiss";

            if (!empty($new_assigned_date)) {
                $update_sql .= ", assigned_date = ?";
                $update_params[] = $new_assigned_date;
                $update_types .= "s";
            }

            $update_sql .= " WHERE id = ?";
            $update_params[] = $task_id_to_update;
            $update_types .= "i";

            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param($update_types, ...$update_params);

            if ($stmt->execute()) {
                $_SESSION['message'] = "Task updated successfully!";
                $_SESSION['message_type'] = 'success';
                $_SESSION['highlight_task_id'] = $task_id_to_update;
            } else {
                $_SESSION['message'] = "Error updating task: " . $stmt->error;
                $_SESSION['message_type'] = 'error';
            }
            $stmt->close();

        } elseif (isset($_POST['complete_task'])) {
            $task_id_to_complete = $_POST['task_id'];
            $stmt = $conn->prepare("UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE id = ?");
            $stmt->bind_param("i", $task_id_to_complete);
            if ($stmt->execute()) {
                $_SESSION['message'] = "Task marked as completed!";
                $_SESSION['message_type'] = 'success';
            }
            $stmt->close();

        } elseif (isset($_POST['delete_task'])) {
            $task_id_to_delete = $_POST['task_id'];
            $stmt = $conn->prepare("DELETE FROM tasks WHERE id = ?");
            $stmt->bind_param("i", $task_id_to_delete);
            if ($stmt->execute()) {
                $_SESSION['message'] = "Task successfully delete ho gaya!";
                $_SESSION['message_type'] = 'success';
            } else {
                $_SESSION['message'] = "Error: Task delete nahi ho saka.";
                $_SESSION['message_type'] = 'error';
            }
            $stmt->close();

        } elseif (isset($_POST['skip_task'])) {
            $task_id_to_skip = $_POST['task_id'];
            $skip_reason = trim($_POST['skip_reason'] ?? '');
            if (empty($skip_reason)) {
                $_SESSION['message'] = "Error: Skip reason is required.";
                $_SESSION['message_type'] = 'error';
            } else {
                $stmt = $conn->prepare("UPDATE tasks SET status = 'Skipped', skip_reason = ? WHERE id = ?");
                $stmt->bind_param("si", $skip_reason, $task_id_to_skip);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Task has been skipped successfully!";
                    $_SESSION['message_type'] = 'success';
                } else {
                    $_SESSION['message'] = "Error: Could not skip task.";
                    $_SESSION['message_type'] = 'error';
                }
                $stmt->close();
            }
        } elseif (isset($_POST['restore_task'])) {
            // =============================================
            // RESTORE TASK LOGIC - Fix: Status set to 'Not Started'
            // =============================================
            $task_id_to_restore = $_POST['task_id'];
            // Yahan status ko 'Not Started' kar diya gaya hai taaki filters mein show ho
            $stmt = $conn->prepare("UPDATE tasks SET status = 'Not Started', skip_reason = NULL WHERE id = ?");
            $stmt->bind_param("i", $task_id_to_restore);
            if ($stmt->execute()) {
                $_SESSION['message'] = "Task successfully restore ho gaya!";
                $_SESSION['message_type'] = 'success';
                $_SESSION['highlight_task_id'] = $task_id_to_restore;
            } else {
                $_SESSION['message'] = "Error: Task restore nahi ho saka.";
                $_SESSION['message_type'] = 'error';
            }
            $stmt->close();
        }
    }
    $query_string = http_build_query($_GET);
    $redirect_url = "master_task_flow.php?" . $query_string;
    header("Location: " . $redirect_url);
    exit();
}

// --- फिल्टर्स ---
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$user_filter_id = $_GET['user_id'] ?? 'all';
$reviewer_filter_id = $_GET['reviewer_id'] ?? 'all';
$status_filter = $_GET['status'] ?? 'active';
$task_type_filter = $_GET['task_type'] ?? 'all';
$search_term = $_GET['search'] ?? '';
$work_type_filter = $_GET['work_type'] ?? 'all';

// --- LOGIC FOR SUMMARY CARDS ---
function getTaskCountForCards($conn, $base_query, $params, $types)
{
    $stmt = mysqli_prepare($conn, $base_query);
    if ($types && count($params) > 0) {
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    }
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);
    return $row ? (int) $row['count'] : 0;
}

$card_base_query_string = "FROM tasks t WHERE t.work_type != 'Report'";
$card_params = [];
$card_param_types = '';

if (!empty($search_term)) {
    $card_base_query_string .= " AND t.client_id IN (SELECT id FROM clients WHERE name LIKE ?)";
    $card_search_like = "%" . $search_term . "%";
    $card_params[] = $card_search_like;
    $card_param_types .= 's';
}
if (!empty($start_date)) {
    $card_base_query_string .= " AND t.assigned_date >= ?";
    $card_params[] = $start_date;
    $card_param_types .= 's';
}
if (!empty($end_date)) {
    $card_base_query_string .= " AND t.assigned_date <= ?";
    $card_params[] = $end_date;
    $card_param_types .= 's';
}
if ($user_filter_id != 'all' && is_numeric($user_filter_id)) {
    $card_base_query_string .= " AND t.assigned_user_id = ?";
    $card_params[] = $user_filter_id;
    $card_param_types .= 'i';
}
if ($reviewer_filter_id != 'all' && is_numeric($reviewer_filter_id)) {
    $card_base_query_string .= " AND t.smm_user_id = ?";
    $card_params[] = $reviewer_filter_id;
    $card_param_types .= 'i';
}
if ($task_type_filter != 'all') {
    $card_base_query_string .= " AND t.task_type = ?";
    $card_params[] = $task_type_filter;
    $card_param_types .= 's';
}
if ($work_type_filter != 'all') {
    $card_base_query_string .= " AND t.work_type = ?";
    $card_params[] = $work_type_filter;
    $card_param_types .= 's';
}

$active_status_filter = " AND t.status NOT IN ('Completed', 'Skipped')";

$total_active_tasks = getTaskCountForCards($conn, "SELECT COUNT(*) as count " . $card_base_query_string . $active_status_filter, $card_params, $card_param_types);
$total_regular_tasks = getTaskCountForCards($conn, "SELECT COUNT(*) as count " . $card_base_query_string . " AND t.task_type = 'Regular'" . $active_status_filter, $card_params, $card_param_types);
$total_additional_tasks = getTaskCountForCards($conn, "SELECT COUNT(*) as count " . $card_base_query_string . " AND t.task_type = 'Additional'" . $active_status_filter, $card_params, $card_param_types);

if (empty($start_date) && empty($end_date)) {
    $completed_default_query = "FROM tasks t WHERE t.work_type != 'Report' AND t.status = 'Completed' AND DATE(t.completed_at) = CURDATE()";
    $completed_default_params = [];
    $completed_default_types = '';

    if (!empty($search_term)) {
        $completed_default_query .= " AND t.client_id IN (SELECT id FROM clients WHERE name LIKE ?)";
        $search_like = "%" . $search_term . "%";
        $completed_default_params[] = $search_like;
        $completed_default_types .= 's';
    }
    if ($user_filter_id != 'all' && is_numeric($user_filter_id)) {
        $completed_default_query .= " AND t.assigned_user_id = ?";
        $completed_default_params[] = $user_filter_id;
        $completed_default_types .= 'i';
    }
    if ($reviewer_filter_id != 'all' && is_numeric($reviewer_filter_id)) {
        $completed_default_query .= " AND t.smm_user_id = ?";
        $completed_default_params[] = $reviewer_filter_id;
        $completed_default_types .= 'i';
    }
    if ($task_type_filter != 'all') {
        $completed_default_query .= " AND t.task_type = ?";
        $completed_default_params[] = $task_type_filter;
        $completed_default_types .= 's';
    }
    $total_completed_tasks = getTaskCountForCards($conn, "SELECT COUNT(*) as count " . $completed_default_query, $completed_default_params, $completed_default_types);
} else {
    $total_completed_tasks = getTaskCountForCards($conn, "SELECT COUNT(*) as count " . $card_base_query_string . " AND t.status = 'Completed'", $card_params, $card_param_types);
}

// --- DATA FETCHING for Table ---
$params = [];
$param_types = '';
$sql = "SELECT t.*, c.name as client_name, u.name as user_name, smm.name as smm_name
    FROM tasks t
    JOIN clients c ON t.client_id = c.id
    JOIN users u ON t.assigned_user_id = u.id
    JOIN users smm ON t.smm_user_id = smm.id
    WHERE t.work_type != 'Report'";

if (!empty($search_term)) {
    $sql .= " AND c.name LIKE ?";
    $search_like = "%" . $search_term . "%";
    $params[] = $search_like;
    $param_types .= 's';
}
if ($status_filter == 'active') {
    $sql .= " AND t.status NOT IN ('Completed', 'Skipped')";
} elseif ($status_filter != 'all') {
    $sql .= " AND t.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}
if ($task_type_filter != 'all') {
    $sql .= " AND t.task_type = ?";
    $params[] = $task_type_filter;
    $param_types .= 's';
}
if ($work_type_filter != 'all') {
    $sql .= " AND t.work_type = ?";
    $params[] = $work_type_filter;
    $param_types .= 's';
}
if (!empty($start_date)) {
    $sql .= " AND t.assigned_date >= ?";
    $params[] = $start_date;
    $param_types .= 's';
}
if (!empty($end_date)) {
    $sql .= " AND t.assigned_date <= ?";
    $params[] = $end_date;
    $param_types .= 's';
}
if ($user_filter_id != 'all' && is_numeric($user_filter_id)) {
    $sql .= " AND t.assigned_user_id = ?";
    $params[] = $user_filter_id;
    $param_types .= 'i';
}
if ($reviewer_filter_id != 'all' && is_numeric($reviewer_filter_id)) {
    $sql .= " AND t.smm_user_id = ?";
    $params[] = $reviewer_filter_id;
    $param_types .= 'i';
}

$sql .= " ORDER BY t.created_at DESC, FIELD(t.priority, 'High', 'Medium', 'Low')";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$tasks_result = $stmt->get_result();
$all_tasks = $tasks_result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$all_employees_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$all_employees = $all_employees_result->fetch_all(MYSQLI_ASSOC);

$reviewers_result = $conn->query("
    SELECT DISTINCT u.id, u.name FROM users u
    JOIN user_roles ur ON u.id = ur.user_id
    JOIN roles r ON ur.role_id = r.id
    WHERE r.name IN ('Manager', 'SMM')
    ORDER BY u.name ASC
");
$all_reviewers = $reviewers_result->fetch_all(MYSQLI_ASSOC);

require_once 'header.php';
?>

<title>Task Flow Dashboard - Digify OS</title>

<style>
    @keyframes fadeOutYellow {
        from { background-color: #fff3cd; }
        to { background-color: transparent; }
    }
    .highlight-row {
        animation: fadeOutYellow 4s ease-in-out;
    }
</style>

<div class="flex-1" x-data="{ isEditModalOpen: false, isDetailsModalOpen: false, isDeleteConfirmOpen: false, currentTask: {} }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">Master Task Flow</h2>
    </header>

    <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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            <div class="bg-blue-500 text-white p-4 rounded-lg shadow-md flex flex-col justify-between">
                <h3 class="text-lg font-semibold">Total Active Tasks</h3>
                <p class="text-3xl font-bold text-right"><?php echo $total_active_tasks; ?></p>
            </div>
            <div class="bg-green-500 text-white p-4 rounded-lg shadow-md flex flex-col justify-between">
                <h3 class="text-lg font-semibold">Active Regular Tasks</h3>
                <p class="text-3xl font-bold text-right"><?php echo $total_regular_tasks; ?></p>
            </div>
            <div class="bg-yellow-500 text-white p-4 rounded-lg shadow-md flex flex-col justify-between">
                <h3 class="text-lg font-semibold">Active Additional Tasks</h3>
                <p class="text-3xl font-bold text-right"><?php echo $total_additional_tasks; ?></p>
            </div>
            <div class="bg-purple-500 text-white p-4 rounded-lg shadow-md flex flex-col justify-between">
                <h3 class="text-lg font-semibold">Completed Tasks</h3>
                <p class="text-3xl font-bold text-right"><?php echo $total_completed_tasks; ?></p>
            </div>
        </div>

        <div class="bg-white p-4 rounded-lg shadow-md mb-8 sticky top-0 z-10">
            <form method="GET" action="master_task_flow.php">
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-8 gap-4 items-end">
                    <div class="flex-grow">
                        <label class="text-sm font-medium text-gray-700">Search by Client</label>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search_term); ?>"
                            class="mt-1 w-full border-gray-300 rounded-md shadow-sm" placeholder="Client name...">
                    </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); ?>"
                            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); ?>"
                            class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Assigned To</label>
                        <select name="user_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                            <option value="all">All Users</option>
                            <?php foreach ($all_employees as $emp): ?>
                                <option value="<?php echo $emp['id']; ?>" <?php if ($user_filter_id == $emp['id']) echo 'selected'; ?>><?php echo htmlspecialchars($emp['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Reviewer</label>
                        <select name="reviewer_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                            <option value="all">All Reviewers</option>
                            <?php foreach ($all_reviewers as $rev): ?>
                                <option value="<?php echo $rev['id']; ?>" <?php if ($reviewer_filter_id == $rev['id']) echo 'selected'; ?>><?php echo htmlspecialchars($rev['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Status</label>
                        <select name="status" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                            <option value="active" <?php if ($status_filter == 'active') echo 'selected'; ?>>All Active</option>
                            <option value="Completed" <?php if ($status_filter == 'Completed') echo 'selected'; ?>>Completed</option>
                            <option value="all" <?php if ($status_filter == 'all') echo 'selected'; ?>>All (incl. Skipped)</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Task Type</label>
                        <select name="task_type" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                            <option value="all" <?php if ($task_type_filter == 'all') echo 'selected'; ?>>All Types</option>
                            <option value="Regular" <?php if ($task_type_filter == 'Regular') echo 'selected'; ?>>Regular</option>
                            <option value="Additional" <?php if ($task_type_filter == 'Additional') echo 'selected'; ?>>Additional</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-sm font-medium text-gray-700">Type of Work</label>
                        <select name="work_type" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                            <option value="all" <?php if ($work_type_filter == 'all') echo 'selected'; ?>>All Work</option>
                            <option value="Post" <?php if ($work_type_filter == 'Post') echo 'selected'; ?>>Post</option>
                            <option value="Reel" <?php if ($work_type_filter == 'Reel') echo 'selected'; ?>>Reel</option>
                            <option value="Story" <?php if ($work_type_filter == 'Story') echo 'selected'; ?>>Story</option>
                            <option value="Other" <?php if ($work_type_filter == 'Other') echo 'selected'; ?>>Other</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-2">
                        <a href="master_task_flow.php" class="px-4 py-2 text-sm text-gray-600 hover:underline">Reset</a>
                        <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="bg-white rounded-lg shadow-lg overflow-hidden">
            <div class="overflow-y-auto">
                <table class="min-w-full">
                    <thead class="bg-gray-100">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Client & Task</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Assigned To / Reviewer</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Status & Details</th>
                            <?php if ($is_admin_or_manager): ?><th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th><?php endif; ?>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($all_tasks)): ?>
                            <tr>
                                <td colspan="4" class="px-6 py-10 text-center text-gray-500">No tasks found for the selected criteria.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($all_tasks as $task): ?>
                                <?php
                                $assigned_time = new DateTime($task['created_at']);
                                $current_time = new DateTime();
                                $interval = $current_time->diff($assigned_time);
                                $hours_passed = ($interval->days * 24) + $interval->h;
                                $border_color_class = 'border-l-4 border-gray-200';
                                $age_text_color = 'text-gray-500';
                                if ($task['status'] == 'Rejected') {
                                    $border_color_class = 'border-l-4 border-red-500';
                                    $age_text_color = 'text-red-600';
                                } elseif ($hours_passed >= 36) {
                                    $border_color_class = 'border-l-4 border-red-500';
                                    $age_text_color = 'text-red-600';
                                } elseif ($hours_passed >= 24) {
                                    $border_color_class = 'border-l-4 border-yellow-400';
                                    $age_text_color = 'text-yellow-600';
                                }
                                $priority_color_class = 'bg-gray-200 text-gray-800';
                                if ($task['priority'] == 'Medium') {
                                    $priority_color_class = 'bg-yellow-200 text-yellow-800';
                                } elseif ($task['priority'] == 'High') {
                                    $priority_color_class = 'bg-red-200 text-red-800';
                                }
                                ?>
                                <tr id="task-<?php echo $task['id']; ?>" class="<?php echo $border_color_class; ?> <?php if ($task['id'] == $highlight_task_id) echo 'highlight-row'; ?>">
                                    <td class="px-6 py-3">
                                        <div class="text-sm font-semibold text-gray-900"><?php echo htmlspecialchars($task['client_name']); ?></div>
                                        <div class="text-sm text-gray-600"><?php echo htmlspecialchars($task['title']); ?></div>
                                        <div class="text-xs text-gray-500 mt-1">Date: <?php echo date("d M, Y", strtotime($task['assigned_date'])); ?></div>
                                        <?php if (!empty($task['description'])): ?>
                                            <button @click="isDetailsModalOpen = true; currentTask = <?php echo htmlspecialchars(json_encode($task)); ?>" class="text-xs text-blue-600 hover:underline mt-1">View Details</button>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-3">
                                        <div class="text-sm text-gray-900"><?php echo htmlspecialchars($task['user_name']); ?></div>
                                        <div class="text-xs text-gray-500">Review: <?php echo htmlspecialchars($task['smm_name']); ?></div>
                                    </td>
                                    <td class="px-6 py-3 text-sm">
                                        <div class="flex items-center gap-2">
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php if ($task['status'] == 'In Review') echo 'bg-yellow-100 text-yellow-800'; elseif ($task['status'] == 'Rejected') echo 'bg-red-100 text-red-800'; else echo 'bg-blue-100 text-blue-800'; ?>"><?php echo htmlspecialchars($task['status']); ?></span>
                                            <span class="px-2 py-0.5 inline-block rounded-full text-xs font-semibold <?php echo $priority_color_class; ?>"><?php echo htmlspecialchars($task['priority']); ?></span>
                                        </div>
                                        <div class="text-xs font-semibold mt-1 <?php echo $age_text_color; ?>">Assigned: <?php echo $interval->d > 0 ? $interval->d . 'd ago' : $interval->h . 'h ago'; ?></div>
                                        <div class="text-xs text-gray-500 mt-1">Work Type: <span class="font-semibold text-gray-700"><?php echo htmlspecialchars($task['work_type']); ?></span></div>
                                    </td>

                                    <?php if ($is_admin_or_manager): ?>
                                        <td class="px-6 py-3 text-sm font-medium" x-data="{ showSkipForm: false }">
                                            <?php if ($task['status'] != 'Completed' && $task['status'] != 'Skipped'): ?>
                                                <div x-show="!showSkipForm" class="flex items-center gap-3">
                                                    <button @click="isEditModalOpen = true; currentTask = <?php echo htmlspecialchars(json_encode($task)); ?>" class="text-indigo-600 hover:text-indigo-900 font-medium">Edit</button>
                                                    <span class="text-gray-300">|</span>
                                                    <button @click="showSkipForm = true" type="button" class="text-yellow-600 hover:text-yellow-800 font-medium">Skip</button>
                                                </div>
                                                <div x-show="showSkipForm" class="p-3 bg-yellow-50 border border-yellow-200 rounded-lg w-64">
                                                    <form method="POST" action="master_task_flow.php?<?php echo http_build_query($_GET); ?>">
                                                        <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                                        <label class="block text-xs font-semibold text-gray-700 mb-1">Reason for Skipping</label>
                                                        <textarea name="skip_reason" rows="2" required placeholder="Enter reason..." class="w-full text-xs border-gray-300 rounded-md shadow-sm focus:ring-yellow-400 focus:border-yellow-400"></textarea>
                                                        <div class="flex items-center justify-between mt-2">
                                                            <button @click="showSkipForm = false" type="button" class="text-xs text-gray-500 hover:underline">Cancel</button>
                                                            <button type="submit" name="skip_task" value="1" class="px-3 py-1 bg-yellow-500 text-white text-xs font-semibold rounded-md hover:bg-yellow-600">Confirm Skip</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            <?php elseif ($task['status'] == 'Skipped'): ?>
                                                <div class="flex items-center gap-2">
                                                    <span class="px-2 py-1 bg-gray-100 text-gray-500 text-xs rounded-full font-medium">Skipped</span>
                                                    <form method="POST" action="master_task_flow.php?<?php echo http_build_query($_GET); ?>" style="display:inline;">
                                                        <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                                        <button type="submit" name="restore_task" class="text-xs text-green-600 hover:underline font-semibold">Restore</button>
                                                    </form>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    <?php endif; ?>

                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <div x-show="isEditModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-50 flex items-center justify-center z-40" @keydown.escape.window="isEditModalOpen = false" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="isEditModalOpen = false">
            <h3 class="text-xl font-semibold mb-2">Edit Task</h3>
            <p class="text-sm text-gray-600 mb-6" x-text="`Task for: ${currentTask.client_name}`"></p>
            <form method="POST" action="master_task_flow.php?<?php echo http_build_query($_GET); ?>">
                <input type="hidden" name="task_id" :value="currentTask.id">
                <div class="space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium">Re-assign To</label>
                            <select name="assigned_user_id" class="mt-1 block w-full border-gray-300 rounded-md">
                                <?php
                                mysqli_data_seek($all_employees_result, 0);
                                $all_employees_for_modal = mysqli_fetch_all($all_employees_result, MYSQLI_ASSOC);
                                foreach($all_employees_for_modal as $emp):
                                ?>
                                <option :selected="currentTask.assigned_user_id == <?php echo $emp['id']; ?>" value="<?php echo $emp['id']; ?>"><?php echo htmlspecialchars($emp['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Change Reviewer (SMM)</label>
                            <select name="smm_user_id" class="mt-1 block w-full border-gray-300 rounded-md">
                                <?php
                                mysqli_data_seek($reviewers_result, 0);
                                $all_reviewers_for_modal = mysqli_fetch_all($reviewers_result, MYSQLI_ASSOC);
                                foreach($all_reviewers_for_modal as $reviewer):
                                ?>
                                <option :selected="currentTask.smm_user_id == <?php echo $reviewer['id']; ?>" value="<?php echo $reviewer['id']; ?>"><?php echo htmlspecialchars($reviewer['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Type of Work</label>
                        <select name="work_type" class="mt-1 block w-full border-gray-300 rounded-md">
                            <option value="Post" :selected="currentTask.work_type === 'Post'">Post</option>
                            <option value="Reel" :selected="currentTask.work_type === 'Reel'">Reel</option>
                            <option value="Story" :selected="currentTask.work_type === 'Story'">Story</option>
                            <option value="Other" :selected="currentTask.work_type === 'Other'">Other</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Reschedule Assigned Date</label>
                        <input type="date" name="assigned_date" :value="currentTask.assigned_date" class="mt-1 block w-full border-gray-300 rounded-md">
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Description</label>
                        <textarea name="description" rows="3" class="mt-1 block w-full border-gray-300 rounded-md" x-text="currentTask.description"></textarea>
                    </div>
                </div>

                <div class="flex justify-between items-center mt-8">
                    <div class="flex items-center gap-2">
                        <button type="submit" name="complete_task" class="px-4 py-2 bg-green-600 text-white rounded-md text-sm hover:bg-green-700">Mark as Completed</button>
                        <button type="button"
                            @click="isEditModalOpen = false; isDeleteConfirmOpen = true"
                            class="px-4 py-2 bg-red-500 text-white text-sm font-semibold rounded-md hover:bg-red-600">
                            Discard Task
                        </button>
                    </div>
                    <div class="flex items-center gap-2">
                        <button type="button" @click="isEditModalOpen = false" class="px-4 py-2 border rounded-md text-sm">Cancel</button>
                        <button type="submit" name="update_task" class="px-4 py-2 bg-blue-600 text-white rounded-md text-sm hover:bg-blue-700">Save Changes</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div x-show="isDeleteConfirmOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-sm text-center">
            <div class="text-5xl mb-4">⚠️</div>
            <h3 class="text-xl font-bold text-gray-800 mb-2">Task Delete Karna Hai?</h3>
            <p class="text-sm text-gray-500 mb-2">Task: <span class="font-semibold text-gray-700" x-text="currentTask.title"></span></p>
            <p class="text-sm text-red-500 mb-6">Yeh task permanently delete ho jaayega. Kya aap sure hain?</p>
            <div class="flex justify-center gap-4">
                <button type="button"
                    @click="isDeleteConfirmOpen = false; isEditModalOpen = true"
                    class="px-5 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 font-medium text-sm">
                    Nahi, Wapas Jao
                </button>
                <form method="POST" action="master_task_flow.php?<?php echo http_build_query($_GET); ?>">
                    <input type="hidden" name="task_id" :value="currentTask.id">
                    <button type="submit" name="delete_task" value="1"
                        class="px-5 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 font-medium text-sm">
                        Haan, Delete Karo
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div x-show="isDetailsModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" @keydown.escape.window="isDetailsModalOpen = false" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="isDetailsModalOpen = false">
            <h3 class="text-xl font-semibold mb-4" x-text="`Details for: ${currentTask.title}`"></h3>
            <p class="text-gray-700 whitespace-pre-wrap" x-text="currentTask.description"></p>
            <div class="flex justify-end mt-6">
                <button @click="isDetailsModalOpen = false" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">Close</button>
            </div>
        </div>
    </div>

</div>

<?php
require_once 'footer.php';
if (isset($conn)) {
    mysqli_close($conn);
}
?>