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

// Suraksha jaanch: Sirf login kiye hue user hi is page ko access kar sakte hain.
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$current_user_id = $_SESSION['user_id'];

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['pull_task'])) {
    $client_id = $_POST['client_id'];
    $task_date = $_POST['task_date'];

    // Validation
    if (empty($client_id) || empty($task_date)) {
        $_SESSION['message'] = "Please select a date and a client.";
        $_SESSION['message_type'] = 'error';
        header("Location: pull_task.php");
        exit();
    }
    
    // SMM User ID prapt karein
    $smm_stmt = $conn->prepare("SELECT smm_user_id FROM task_schedules WHERE client_id = ? AND is_active = TRUE LIMIT 1");
    $smm_stmt->bind_param("i", $client_id);
    $smm_stmt->execute();
    $smm_result = $smm_stmt->get_result();
    if ($smm_result->num_rows === 0) {
         $_SESSION['message'] = "Could not find an active schedule to determine the SMM for this client.";
         $_SESSION['message_type'] = 'error';
         header("Location: pull_task.php");
         exit();
    }
    $smm_user_id = $smm_result->fetch_assoc()['smm_user_id'];
    $smm_stmt->close();

    // Client ka naam prapt karein
    $client_stmt = $conn->prepare("SELECT name FROM clients WHERE id = ?");
    $client_stmt->bind_param("i", $client_id);
    $client_stmt->execute();
    $client_name = $client_stmt->get_result()->fetch_assoc()['name'];
    $client_stmt->close();

    $task_title = "Regular Task for " . $client_name;

    // Naya task banayein
    $insert_sql = "INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, task_type, work_type, assigned_date, priority) VALUES (?, ?, ?, ?, 'Regular', 'Reel', ?, 'Medium')";
    $stmt_insert = $conn->prepare($insert_sql);
    $stmt_insert->bind_param("iisss", $client_id, $current_user_id, $smm_user_id, $task_title, $task_date);

    if ($stmt_insert->execute()) {
        $_SESSION['message'] = "Task for '" . htmlspecialchars($client_name) . "' has been assigned to you for " . date("d M, Y", strtotime($task_date)) . ".";
        $_SESSION['message_type'] = 'success';
    } else {
        $_SESSION['message'] = "Error: Could not pull the task. It might have been pulled by someone else.";
        $_SESSION['message_type'] = 'error';
    }
    $stmt_insert->close();
    $conn->close();
    header("Location: my_tasks.php");
    exit();
}

require_once 'header.php';
?>

<title>Pull Advance Task - Digify OS</title>

<main class="p-6 md:p-10">
    <div class="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow-lg">
        <h2 class="text-2xl font-bold text-gray-800 mb-2">Pull Advance Task</h2>
        <p class="text-gray-600 mb-6">First, select a date to see a list of clients with scheduled tasks for that day. Then, you can pull a task to work on.</p>

        <form method="POST" action="pull_task.php" id="pullTaskForm">
            <div class="space-y-6">
                <div>
                    <label for="task_date" class="block text-sm font-medium text-gray-700">1. Select a Date</label>
                    <input type="date" id="task_date" name="task_date" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"
                           min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>">
                </div>

                <div>
                    <label for="client_id" class="block text-sm font-medium text-gray-700">2. Select a Client</label>
                    <select id="client_id" name="client_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" disabled>
                        <option value="">-- First Select a Date --</option>
                    </select>
                    <div id="loading" class="mt-2 text-sm text-blue-600" style="display: none;">
                        <svg class="animate-spin h-5 w-5 mr-3 inline-block" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                        Loading clients...
                    </div>
                </div>
            </div>

            <div class="mt-8 border-t pt-5">
                <div class="flex justify-end">
                    <a href="my_tasks.php" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">Cancel</a>
                    <button type="submit" name="pull_task" id="pull_task_btn" class="ml-3 px-4 py-2 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700" disabled>
                        Pull Task
                    </button>
                </div>
            </div>
        </form>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const dateInput = document.getElementById('task_date');
    const clientSelect = document.getElementById('client_id');
    const pullButton = document.getElementById('pull_task_btn');
    const loadingDiv = document.getElementById('loading');

    dateInput.addEventListener('change', function() {
        const selectedDate = this.value;
        // Reset and disable the client select and button
        clientSelect.innerHTML = '<option value="">-- Loading... --</option>';
        clientSelect.disabled = true;
        pullButton.disabled = true;

        if (!selectedDate) {
            clientSelect.innerHTML = '<option value="">-- First Select a Date --</option>';
            return;
        }

        loadingDiv.style.display = 'block';

        // API ko call karein
        fetch(`api_get_scheduled_clients.php?date=${selectedDate}`)
            .then(response => response.json())
            .then(data => {
                loadingDiv.style.display = 'none';
                clientSelect.innerHTML = ''; // Purane options hata dein

                if (data.error) {
                    clientSelect.innerHTML = `<option value="">Error: ${data.error}</option>`;
                } else if (data.length > 0) {
                    clientSelect.disabled = false;
                    pullButton.disabled = false;
                    clientSelect.innerHTML = '<option value="">-- Select a Client --</option>';
                    data.forEach(client => {
                        const option = document.createElement('option');
                        option.value = client.id;
                        option.textContent = client.name;
                        clientSelect.appendChild(option);
                    });
                } else {
                    clientSelect.innerHTML = '<option value="">-- No available clients for this date --</option>';
                }
            })
            .catch(error => {
                loadingDiv.style.display = 'none';
                console.error('Error fetching clients:', error);
                clientSelect.innerHTML = '<option value="">-- Error loading clients --</option>';
            });
    });
});
</script>

<?php
require_once 'footer.php';
?>

