<?php
require_once 'init.php';

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

$message = '';
$error = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['user_id'])) {
    $target_date = $_POST['task_date'];
    $user_id = $_POST['user_id'];
    $client_ids = $_POST['client_ids'] ?? [];

    if (!empty($client_ids)) {
        $conn->begin_transaction();
        try {
            foreach ($client_ids as $client_id) {
                // Sahi Column Names: assigned_user_id aur assigned_date
                $check_sql = "SELECT id FROM tasks WHERE client_id = ? AND assigned_user_id = ? AND assigned_date = ?";
                $check_stmt = $conn->prepare($check_sql);
                
                if (!$check_stmt) throw new Exception("Check Prepare failed: " . $conn->error);

                $check_stmt->bind_param("iis", $client_id, $user_id, $target_date);
                $check_stmt->execute();
                $already_exists = $check_stmt->get_result()->num_rows > 0;
                $check_stmt->close();

                if (!$already_exists) {
                    // SMM ID (Reviewer) fetch karein schedule se
                    $stmt = $conn->prepare("SELECT smm_user_id FROM task_schedules WHERE client_id = ? AND user_id = ? LIMIT 1");
                    $stmt->bind_param("ii", $client_id, $user_id);
                    $stmt->execute();
                    $smm_id = $stmt->get_result()->fetch_assoc()['smm_user_id'] ?? 0;
                    $stmt->close();

                    // Task insertion with correct columns
                    $ins_sql = "INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, task_type, status, assigned_date) 
                                VALUES (?, ?, ?, 'Regular Task (Advance)', 'Regular', 'Not Started', ?)";
                    $ins = $conn->prepare($ins_sql);
                    
                    if (!$ins) throw new Exception("Insert prepare failed: " . $conn->error);
                    
                    $ins->bind_param("iiis", $client_id, $user_id, $smm_id, $target_date);
                    $ins->execute();
                    $ins->close();
                }
            }
            $conn->commit();
            $message = "Tasks successfully generated for " . date('d-M-Y', strtotime($target_date));
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Logic Error: " . $e->getMessage();
        }
    }
}

// Roles Filter: Designer aur Editor fetch karein
$user_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 ('Graphic Designer', 'Video Editor') ORDER BY u.name ASC";
$all_users = $conn->query($user_query)->fetch_all(MYSQLI_ASSOC);

require_once 'header.php';
?>

<div class="max-w-4xl mx-auto p-8 bg-white shadow-xl rounded-2xl mt-10" x-data="taskFlow()">
    <h2 class="text-2xl font-bold text-gray-800 mb-6 border-b pb-4">Advance Task Assignment</h2>

    <?php if($message): ?><div class="p-4 mb-6 bg-green-100 text-green-700 rounded-lg font-bold">✓ <?php echo $message; ?></div><?php endif; ?>
    <?php if($error): ?><div class="p-4 mb-6 bg-red-100 text-red-700 rounded-lg font-bold">⚠ <?php echo $error; ?></div><?php endif; ?>

    <form method="POST" @submit="return validateSubmission()">
        <div class="space-y-8">
            <div>
                <label class="block text-sm font-bold text-gray-700">1. Select Employee</label>
                <select name="user_id" x-model="userVal" @change="resetNext()" required class="mt-1 block w-full border-gray-300 rounded-md">
                    <option value="">-- Choose Designer/Editor --</option>
                    <?php foreach($all_users as $u): ?>
                        <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div x-show="userVal">
                <label class="block text-sm font-bold text-gray-700 mb-3">2. Select Schedule Group</label>
                <div class="flex gap-4">
                    <button type="button" @click="setGroup('Daily')" :class="typeVal === 'Daily' ? 'bg-blue-600 text-white' : 'bg-gray-100'" class="px-6 py-2 rounded-full font-bold border">Daily</button>
                    <button type="button" @click="setGroup('GroupA')" :class="typeVal === 'GroupA' ? 'bg-purple-600 text-white' : 'bg-gray-100'" class="px-6 py-2 rounded-full font-bold border">Group A (M,W,F)</button>
                    <button type="button" @click="setGroup('GroupB')" :class="typeVal === 'GroupB' ? 'bg-green-600 text-white' : 'bg-gray-100'" class="px-6 py-2 rounded-full font-bold border">Group B (T,T,S)</button>
                </div>
            </div>

            <div x-show="clients.length > 0">
                <label class="block text-sm font-bold text-gray-700 mb-4 uppercase">3. Select Clients (Tick for Multiple)</label>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3 bg-gray-50 p-4 rounded-xl border max-h-60 overflow-y-auto">
                    <template x-for="c in clients" :key="c.id">
                        <label class="flex items-center p-3 bg-white border rounded shadow-sm cursor-pointer hover:border-blue-400">
                            <input type="checkbox" name="client_ids[]" :value="c.id" checked class="h-5 w-5 text-blue-600 rounded">
                            <span class="ml-3 text-sm font-semibold" x-text="c.name"></span>
                        </label>
                    </template>
                </div>
            </div>

            <div x-show="clients.length > 0">
                <label class="block text-sm font-bold text-gray-700">4. Select Task Date</label>
                <input type="date" name="task_date" x-model="dateVal" @change="validateDate()" required class="mt-1 block w-full border-gray-300 rounded-md">
                <p x-show="dateError" class="text-red-600 text-sm mt-2 font-bold" x-text="dateError"></p>
            </div>

            <div x-show="loading" class="text-center py-4 text-blue-600 font-bold animate-pulse">Loading clients...</div>

            <button type="submit" x-show="dateVal && !dateError && clients.length > 0" class="w-full bg-indigo-700 text-white font-bold py-4 rounded-xl shadow-lg hover:bg-indigo-800 transition">
                🚀 GENERATE ADVANCE TASKS
            </button>
        </div>
    </form>
</div>

<script>
function taskFlow() {
    return {
        userVal: '', typeVal: '', dateVal: '', clients: [], loading: false, dateError: '',
        resetNext() { this.typeVal = ''; this.clients = []; this.dateVal = ''; this.dateError = ''; },
        setGroup(g) { this.typeVal = g; this.loadClients(); },
        loadClients() {
            if(!this.userVal || !this.typeVal) return;
            this.loading = true;
            fetch(`api_get_manual_schedules.php?user_id=${this.userVal}&type=${this.typeVal}`)
                .then(r => r.json())
                .then(d => { this.clients = d; this.loading = false; });
        },
        validateDate() {
            if(!this.dateVal) return;
            const d = new Date(this.dateVal);
            const day = d.getDay(); 
            this.dateError = '';
            if (day === 0) { this.dateError = "Sundays are off."; return; }
            if (this.typeVal === 'GroupA' && ![1, 3, 5].includes(day)) {
                this.dateError = "Group A only Mon, Wed, or Fri.";
            } else if (this.typeVal === 'GroupB' && ![2, 4, 6].includes(day)) {
                this.dateError = "Group B only Tue, Thu, or Sat.";
            }
        },
        validateSubmission() { this.validateDate(); return this.dateError === ''; }
    }
}
</script>

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