<?php
require_once 'init.php';

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

$message = '';
$message_type = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Ab client_ids ek array hoga
    $client_ids = $_POST['client_ids'] ?? [];
    $assigned_user_id = $_POST['assigned_user_id'];
    $smm_user_id = $_POST['smm_user_id'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $work_type = $_POST['work_type'];
    $assigned_date = $_POST['assigned_date'];
    $priority = $_POST['priority'];
    $created_by_id = $_SESSION['user_id'];

    // Form validation
    if (empty($client_ids) || empty($assigned_user_id) || empty($smm_user_id) || empty($title) || empty($assigned_date) || empty($priority)) {
        $message = "Please fill all the required fields.";
        $message_type = 'error';
    } else {
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, description, work_type, assigned_date, priority, task_type, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Additional', 'Not Started', ?)");

            if (!$stmt) {
                throw new Exception("Database error: Could not prepare the statement. MySQL Error: " . $conn->error);
            }
            
            // Har select kiye gaye client ke liye ek task banayein
            foreach ($client_ids as $client_id) {
                $stmt->bind_param("iiisssssi", $client_id, $assigned_user_id, $smm_user_id, $title, $description, $work_type, $assigned_date, $priority, $created_by_id);
                if (!$stmt->execute()) {
                    throw new Exception("Error creating task for a client: " . $stmt->error);
                }
            }
            
            $stmt->close();
            $conn->commit();

            $_SESSION['message'] = "Additional task(s) created successfully!";
            $_SESSION['message_type'] = 'success';
            header("Location: my_tasks.php"); // Safalta par redirect karein
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $message = $e->getMessage();
            $message_type = 'error';
        }
    }
}

// Data fetching for form dropdowns
$clients_result = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");
$clients = $clients_result->fetch_all(MYSQLI_ASSOC);

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

// FIX: DISTINCT ka istemaal karke duplicate reviewers ko hata diya gaya hai.
$smm_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 ('Admin', 'Manager') ORDER BY u.name ASC");
$smms = $smm_result->fetch_all(MYSQLI_ASSOC);

require_once 'header.php';
?>

<title>Add Additional Task - Digify OS</title>

<!-- Tom Select CSS for multi-select dropdown -->
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>


<div class="p-6 md:p-10">
    <header class="mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Add Additional Task</h2>
        <p class="text-gray-600">Create a new one-time task for multiple clients and assign it to a team member.</p>
    </header>

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

    <div class="bg-white p-8 rounded-lg shadow-md max-w-2xl mx-auto">
        <form method="POST" action="add_additional_task.php">
            <div class="space-y-6">
                <!-- Client Multi-Select -->
                <div>
                    <label for="client_ids" class="block text-sm font-medium text-gray-700">Client(s) <span class="text-red-500">*</span></label>
                    <select id="client_ids" name="client_ids[]" required multiple placeholder="Select one or more clients...">
                        <?php foreach ($clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Assigned To -->
                    <div>
                        <label for="assigned_user_id" class="block text-sm font-medium text-gray-700">Assign To <span class="text-red-500">*</span></label>
                        <select id="assigned_user_id" name="assigned_user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option value="">-- Select a User --</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <!-- SMM / Reviewer -->
                    <div>
                        <label for="smm_user_id" class="block text-sm font-medium text-gray-700">Reviewer (Admin/Manager) <span class="text-red-500">*</span></label>
                        <select id="smm_user_id" name="smm_user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option value="">-- Select a Reviewer --</option>
                            <?php foreach ($smms as $smm): ?>
                                <option value="<?php echo $smm['id']; ?>"><?php echo htmlspecialchars($smm['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Task Title -->
                <div>
                    <label for="title" class="block text-sm font-medium text-gray-700">Task Title <span class="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" placeholder="e.g., Create carousel for Diwali post">
                </div>

                <!-- Task Description -->
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea id="description" name="description" rows="4" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" placeholder="Provide more details about the task..."></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <!-- Work Type -->
                    <div>
                        <label for="work_type" class="block text-sm font-medium text-gray-700">Type of Work</label>
                        <select id="work_type" name="work_type" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option>Post</option>
                            <option>Reel</option>
                            <option>Story</option>
                            <option>Other</option>
                        </select>
                    </div>
                    <!-- Assigned Date -->
                    <div>
                        <label for="assigned_date" class="block text-sm font-medium text-gray-700">Date <span class="text-red-500">*</span></label>
                        <input type="date" id="assigned_date" name="assigned_date" required value="<?php echo date('Y-m-d'); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    </div>
                    <!-- Priority -->
                    <div>
                        <label for="priority" class="block text-sm font-medium text-gray-700">Priority <span class="text-red-500">*</span></label>
                        <select id="priority" name="priority" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                            <option>Medium</option>
                            <option>High</option>
                            <option>Low</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="mt-8 pt-5 border-t border-gray-200">
                <div class="flex justify-end">
                    <a href="my_tasks.php" class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50">Cancel</a>
                    <button type="submit" class="ml-3 inline-flex justify-center py-2 px-6 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">Create Task(s)</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    // Initialize Tom Select for the multi-select dropdown
    document.addEventListener('DOMContentLoaded', function() {
        new TomSelect('#client_ids',{
            plugins: ['remove_button'],
            create: false,
            sortField: {
                field: "text",
                direction: "asc"
            }
        });
    });
</script>

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

