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

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

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

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $employee_id = $_POST['employee_id'];
    $client_id = $_POST['client_id'];
    $smm_user_id = $_POST['smm_user_id'];
    $completed_date = $_POST['completed_date'];
    $work_type = $_POST['work_type']; // 'Post' ya 'Reel'
    $task_type = $_POST['task_type']; // 'Regular' ya 'Additional'
    $task_count = (int)$_POST['task_count'];

    if ($task_count > 0 && $task_count <= 50) { // Ek limit rakhein taaki galti se zyada entries na ho
        $conn->begin_transaction();
        try {
            $task_title = "Manual Entry: " . $work_type;
            
            $stmt = $conn->prepare(
                "INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, task_type, status, priority, assigned_date, completed_at) 
                 VALUES (?, ?, ?, ?, ?, 'Completed', 'Medium', ?, NOW())"
            );

            for ($i = 0; $i < $task_count; $i++) {
                $stmt->bind_param("iissss", $client_id, $employee_id, $smm_user_id, $task_title, $task_type, $completed_date);
                if (!$stmt->execute()) {
                    throw new Exception("Database insert failed: " . $stmt->error);
                }
            }
            
            $conn->commit();
            $stmt->close();
            $message = "Successfully added " . $task_count . " completed task(s) for the user.";
            $message_type = 'success';

        } catch (Exception $e) {
            $conn->rollback();
            $message = "An error occurred: " . $e->getMessage();
            $message_type = 'error';
        }
    } else {
        $message = "Please enter a valid task count (between 1 and 50).";
        $message_type = 'error';
    }
}

// --- Dropdowns ke liye data fetch karna ---
$employees_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$all_employees = $employees_result->fetch_all(MYSQLI_ASSOC);

$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();
?>

<title>Manual Task Entry - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Manually Add Completed Work</h2>

<main class="p-6 md:p-10">
    <div class="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow-lg">
        <p class="text-gray-600 mb-6">
            Use this form to add work that was completed but not tracked in the system. These entries will be marked as 'Completed' and will be included in performance reports.
        </p>

        <?php if (!empty($message)): ?>
            <div class="mb-6 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; ?>

        <form method="POST" action="manual_add_completed_task.php" class="space-y-6">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="employee_id" class="block text-sm font-medium text-gray-700">Select Employee <span class="text-red-500">*</span></label>
                    <select name="employee_id" id="employee_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">-- Select --</option>
                        <?php foreach($all_employees as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>"><?php echo htmlspecialchars($emp['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="client_id" class="block text-sm font-medium text-gray-700">For which Client? <span class="text-red-500">*</span></label>
                    <select name="client_id" id="client_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="">-- Select --</option>
                        <?php foreach($all_clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div>
                <label for="smm_user_id" class="block text-sm font-medium text-gray-700">Reviewer (SMM) <span class="text-red-500">*</span></label>
                <select name="smm_user_id" id="smm_user_id" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    <option value="">-- Select Reviewer --</option>
                    <?php foreach($all_employees as $smm): ?>
                        <option value="<?php echo $smm['id']; ?>"><?php echo htmlspecialchars($smm['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                 <div>
                    <label for="completed_date" class="block text-sm font-medium text-gray-700">Date of Completion <span class="text-red-500">*</span></label>
                    <input type="date" name="completed_date" id="completed_date" required value="<?php echo date('Y-m-d'); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                </div>
                 <div>
                    <label for="task_count" class="block text-sm font-medium text-gray-700">How many tasks? <span class="text-red-500">*</span></label>
                    <input type="number" name="task_count" id="task_count" required value="1" min="1" max="50" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="work_type" class="block text-sm font-medium text-gray-700">Type of Work <span class="text-red-500">*</span></label>
                    <select name="work_type" id="work_type" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="Post">Post</option>
                        <option value="Reel">Reel</option>
                        <option value="Story">Story</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div>
                    <label for="task_type" class="block text-sm font-medium text-gray-700">Task Category <span class="text-red-500">*</span></label>
                    <select name="task_type" id="task_type" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                        <option value="Regular">Regular</option>
                        <option value="Additional">Additional</option>
                    </select>
                </div>
            </div>

            <div class="flex justify-end mt-8 pt-6 border-t">
                <button type="submit" class="px-6 py-2 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700">
                    Add Completed Task(s)
                </button>
            </div>
        </form>
    </div>
</main>

<?php
// footer.php ko shaamil karein
require_once 'footer.php';
?>