<?php
// init.php ko shaamil karein, jo sab kuch setup karega
require_once 'init.php';

// Suraksha jaanch: User log in hona chahiye.
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$user_id = $_SESSION['user_id'];
// Yahan user role check karein, taaki hum button ka link badal sakein
$is_video_editor = userHasRole(['Video Editor']);

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

// --- UPDATE TASK STATUS LOGIC (PRG Pattern ke saath) ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['task_id'])) {
        $task_id = $_POST['task_id'];

        if (isset($_POST['update_status'])) {
            $new_status = $_POST['new_status'];
            $stmt = $conn->prepare("UPDATE tasks SET status = ? WHERE id = ? AND assigned_user_id = ?");
            $stmt->bind_param("sii", $new_status, $task_id, $user_id);
            if ($stmt->execute()) {
                $_SESSION['message'] = "Task status updated successfully!";
                $_SESSION['message_type'] = 'success';
            } else {
                $_SESSION['message'] = "Error: Could not update task.";
                $_SESSION['message_type'] = 'error';
            }
            $stmt->close();
        } elseif (isset($_POST['skip_task'])) {
            $skip_reason = $_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 = ? AND assigned_user_id = ?");
                $stmt->bind_param("sii", $skip_reason, $task_id, $user_id);
                if ($stmt->execute()) {
                    $_SESSION['message'] = "Task has been skipped successfully!";
                    $_SESSION['message_type'] = 'success';
                }
                $stmt->close();
            }
        }
    }
    // Action ke baad page ko redirect karein
    header("Location: my_tasks.php");
    exit();
}


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

// --- DATA FETCHING ---
$params = [$user_id];
$param_types = 'i';
$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 = FALSE";

if ($status_filter == 'active') {
    $sql .= " AND t.status IN ('Not Started', 'In Process', 'Rejected')";
} elseif ($status_filter == 'completed') {
    $sql .= " AND t.status IN ('In Review', 'Completed')";
}

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 FIELD(t.status, 'Rejected') DESC, FIELD(t.priority, 'High', 'Medium', 'Low'), t.created_at ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$tasks = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// --- Task Counts for Stats Cards ---
$today_date = date('Y-m-d');
$stmt_today = $conn->prepare("SELECT COUNT(id) as count FROM tasks WHERE assigned_user_id = ? AND assigned_date = ? AND is_checklist_task = FALSE AND status IN ('Not Started', 'In Process', 'Rejected')");
$stmt_today->bind_param("is", $user_id, $today_date);
$stmt_today->execute();
$todays_active_count = $stmt_today->get_result()->fetch_assoc()['count'];
$stmt_today->close();

$stmt_review = $conn->prepare("SELECT COUNT(id) as count FROM tasks WHERE assigned_user_id = ? AND is_checklist_task = FALSE AND status = 'In Review'");
$stmt_review->bind_param("i", $user_id);
$stmt_review->execute();
$pending_review_count = $stmt_review->get_result()->fetch_assoc()['count'];
$stmt_review->close();

// Advance task popup ke liye user ke scheduled clients
$clients_result = $conn->prepare("SELECT DISTINCT c.id, c.name FROM clients c JOIN task_schedules ts ON c.id = ts.client_id WHERE ts.user_id = ? AND c.is_active = TRUE ORDER BY c.name ASC");
$clients_result->bind_param("i", $user_id);
$clients_result->execute();
$user_clients = $clients_result->get_result()->fetch_all(MYSQLI_ASSOC);
$clients_result->close();

$conn->close();

require_once 'header.php';
?>

<title>My Tasks - Digify OS</title>
<div class="flex-1" x-data="{ isDetailsModalOpen: false, isAdvanceModalOpen: false, taskDescription: '', currentTask: {} }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">My Workspace</h2>
    </header>

<main class="p-6 md:p-10">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-blue-100 p-3 rounded-full"><svg class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" /></svg></div>
            <div>
                <p class="text-sm font-medium text-gray-500">Today's Active Tasks</p>
                <p class="text-3xl font-bold text-gray-800"><?php echo $todays_active_count; ?></p>
            </div>
        </div>
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-yellow-100 p-3 rounded-full"><svg class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></div>
            <div>
                <p class="text-sm font-medium text-gray-500">Tasks Pending Review</p>
                <p class="text-3xl font-bold text-yellow-600"><?php echo $pending_review_count; ?></p>
            </div>
        </div>
    </div>

    <div class="bg-white p-4 rounded-lg shadow-md mb-8">
        <form method="GET" action="my_tasks.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($user_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">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'; ?>>Active (To Do)</option>
                        <option value="completed" <?php if($status_filter == 'completed') echo 'selected'; ?>>Completed & In-Review</option>
                        <option value="all">All</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="my_tasks.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>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded <?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="space-y-4">
        <?php if (empty($tasks)): ?>
            <div class="bg-white p-8 rounded-lg shadow text-center">
                <h3 class="mt-2 text-lg font-medium text-gray-900">No tasks found!</h3>
                <p class="mt-1 text-sm text-gray-500">Either all tasks are completed or none match your filter criteria.</p>
                <div class="mt-6">
                    <!-- ===== YAHAN BADLAV KIYA GAYA HAI ===== -->
                    <?php if ($is_video_editor): ?>
                        <a href="pull_task.php" class="px-6 py-2 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700">Work on Advance Task</a>
                    <?php else: ?>
                         <button @click="isAdvanceModalOpen = true" class="px-6 py-2 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700">Work on Advance Task</button>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($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;
                    $highlight_class = ($hours_passed > 4 && $task['status'] == 'Not Started') ? 'border-l-4 border-red-500' : 'border-l-4 border-gray-200';
                ?>
                <div class="bg-white rounded-lg shadow-md overflow-hidden <?php echo $highlight_class; ?>" x-data="{ showSkipForm: false }">
                    <div class="p-4">
                        <div class="flex flex-col md:flex-row justify-between items-start gap-4">
                            <div class="flex-grow">
                                <p class="text-sm font-semibold text-gray-500"><?php echo htmlspecialchars($task['client_name']); ?></p>
                                <p class="text-lg font-bold text-gray-900 mt-1"><?php echo htmlspecialchars($task['title']); ?></p>
                                <?php if($task['task_type'] == 'Additional' && !empty($task['description'])): ?>
                                    <button @click="isDetailsModalOpen = true; taskDescription = `<?php echo htmlspecialchars(addslashes($task['description'])); ?>`" class="text-xs text-blue-600 hover:underline mt-1">View Details</button>
                                <?php endif; ?>
                                <?php if($task['status'] == 'Rejected' && !empty($task['rejection_reason'])): ?><p class="mt-2 text-xs text-red-600 p-2 bg-red-50 rounded"><strong>Rework Reason:</strong> <?php echo htmlspecialchars($task['rejection_reason']); ?></p><?php endif; ?>
                            </div>
                            <div class="flex-shrink-0 w-full md:w-auto">
                                <div x-show="!showSkipForm">
                                    <form method="POST" action="my_tasks.php" class="flex items-center gap-2">
                                        <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                        <select name="new_status" class="text-sm rounded-md border-gray-300 shadow-sm">
                                            <option value="Not Started" <?php if($task['status'] == 'Not Started') echo 'selected'; ?>>Not Started</option>
                                            <option value="In Process" <?php if($task['status'] == 'In Process') echo 'selected'; ?>>In Process</option>
                                            <option value="In Review">Completed (Send for Review)</option>
                                        </select>
                                        <button type="submit" name="update_status" class="px-3 py-2 bg-indigo-600 text-white text-xs font-semibold rounded-lg shadow-md hover:bg-indigo-700">Update</button>
                                        
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="border-t mt-4 pt-3 flex items-center text-center text-xs text-gray-500">
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Assigned Date</strong>
                                <span><?php echo date("d M, Y", strtotime($task['assigned_date'])); ?></span>
                            </div>
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Assigned Time</strong>
                                <span><?php echo $interval->d > 0 ? $interval->d . 'd ago' : $interval->h . 'h ago'; ?></span>
                            </div>
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Work Type</strong>
                                <span class="font-semibold text-gray-700"><?php echo htmlspecialchars($task['work_type']); ?></span>
                            </div>
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Priority</strong>
                                <span class="font-semibold text-gray-700"><?php echo htmlspecialchars($task['priority']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</main>

<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">
    <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">Task Description</h3>
        <p class="text-gray-700 whitespace-pre-wrap" x-text="taskDescription"></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 x-show="isAdvanceModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" @keydown.escape.window="isAdvanceModalOpen = false">
    <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-md" @click.away="isAdvanceModalOpen = false">
        <h3 class="text-xl font-semibold mb-4">Pull Next Regular Task</h3>
        <p class="text-sm text-gray-600 mb-6">Select a client to pull their next upcoming scheduled task into your workspace.</p>
        <form method="POST" action="create_advance_task.php">
            <div>
                <label for="client_id_modal" class="block text-sm font-medium text-gray-700">Select Client</label>
                <select name="client_id" id="client_id_modal" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    <option value="">-- Select Your Client --</option>
                    <?php foreach($user_clients as $client): ?>
                        <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="flex justify-end mt-6">
                <button type="button" @click="isAdvanceModalOpen = false" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">Cancel</button>
                <button type="submit" name="pull_task" class="ml-3 px-4 py-2 bg-blue-600 text-white rounded-md">Pull Task</button>
            </div>
        </form>
    </div>
</div>

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