<?php
require_once 'init.php';

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

// --- RESTORE TASK LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['restore_task'])) {
    $task_id_to_restore = (int)$_POST['task_id'];
    
    // Status ko 'Not Started' karna taaki wo active task flow mein dikhne lage
    // assigned_date ko nahi chheda gaya hai
    $stmt = $conn->prepare("UPDATE tasks SET status = 'Not Started', skip_reason = NULL WHERE id = ?");
    $stmt->bind_param("i", $task_id_to_restore);
    
    if ($stmt->execute()) {
        $_SESSION['message'] = "Task successfully restored to Active Flow!";
        $_SESSION['message_type'] = 'success';
    } else {
        $_SESSION['message'] = "Error: Could not restore task.";
        $_SESSION['message_type'] = 'error';
    }
    $stmt->close();
    
    header("Location: skipped_tasks.php");
    exit();
}

$items_per_page = 10;

// --- AJAX FETCH LOGIC ---
if (isset($_GET['fetch_ajax'])) {
    header('Content-Type: application/json');
    $page = (int)($_GET['page'] ?? 1);
    $offset = ($page - 1) * $items_per_page;

    $client_search = $conn->real_escape_string($_GET['client_search'] ?? '');
    $assignee_search = $conn->real_escape_string($_GET['assignee_search'] ?? '');
    $reviewer_id = $_GET['reviewer_id'] ?? 'all';
    
    $start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-45 days')); // Range badha di gayi hai default mein
    $end_date = $_GET['end_date'] ?? date('Y-m-d');

    $sql = "SELECT t.*, c.name as client_name, u.name as assignee_name, r.name as reviewer_name 
            FROM tasks t
            JOIN clients c ON t.client_id = c.id
            JOIN users u ON t.assigned_user_id = u.id
            LEFT JOIN users r ON t.smm_user_id = r.id
            WHERE t.status = 'Skipped'";

    if ($client_search != '') $sql .= " AND c.name LIKE '%$client_search%'";
    if ($assignee_search != '') $sql .= " AND u.name LIKE '%$assignee_search%'";
    if ($reviewer_id != 'all') {
        $rev_id = (int)$reviewer_id;
        $sql .= " AND t.smm_user_id = $rev_id";
    }
    
    $sql .= " AND (t.assigned_date BETWEEN '$start_date' AND '$end_date')";
    
    // Sort logic change: ID DESC se recent activities uper aayengi
    $sql .= " ORDER BY t.id DESC LIMIT $items_per_page OFFSET $offset";

    $res = $conn->query($sql);
    echo json_encode($res ? $res->fetch_all(MYSQLI_ASSOC) : []);
    exit();
}

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

// --- DATA FOR FILTERS ---
$reviewers_res = $conn->query("SELECT id, name FROM users WHERE id IN (SELECT DISTINCT user_id FROM user_roles JOIN roles ON user_roles.role_id = roles.id WHERE roles.name IN ('Admin', 'Manager')) ORDER BY name ASC");
$reviewers_list = ($reviewers_res) ? $reviewers_res->fetch_all(MYSQLI_ASSOC) : [];
$staff_res = $conn->query("SELECT name FROM users ORDER BY name ASC");
$all_staff = ($staff_res) ? $staff_res->fetch_all(MYSQLI_ASSOC) : [];
$clients_res = $conn->query("SELECT name FROM clients WHERE is_active = 1");
$all_clients = ($clients_res) ? $clients_res->fetch_all(MYSQLI_ASSOC) : [];

require_once 'header.php';
?>

<style>
    .custom-scroll::-webkit-scrollbar { width: 6px; }
    .custom-scroll::-webkit-scrollbar-track { background: transparent; }
    .custom-scroll::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    
    .vault-card {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .vault-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
        border-color: #ef4444;
    }
</style>

<div class="flex-1 bg-slate-50 h-screen flex flex-col overflow-hidden" x-data="skippedTasksHandler()">
    
    <!-- Modern Header Section -->
    <div class="flex-none bg-white border-b border-slate-200 z-50 shadow-sm relative overflow-hidden">
        <div class="absolute top-0 right-0 -mt-10 -mr-10 w-40 h-40 bg-red-500/5 rounded-full blur-3xl"></div>
        
        <header class="px-8 py-6 flex justify-between items-center">
            <div>
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-red-600 rounded-lg shadow-lg shadow-red-200">
                        <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                    </div>
                    <h2 class="text-3xl font-black text-slate-800 uppercase tracking-tighter">Skipped Vault</h2>
                </div>
                <div class="flex items-center gap-2 mt-2 ml-1">
                    <span class="w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Archive of skipped assignments</p>
                </div>
            </div>
        </header>

        <!-- Message Box -->
        <?php if ($message): ?>
        <div class="px-8 mb-4">
            <div class="p-4 rounded-2xl text-sm font-bold flex items-center gap-3 <?= $message_type == 'success' ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-red-50 text-red-700 border border-red-100' ?>">
                <div class="w-2 h-2 rounded-full <?= $message_type == 'success' ? 'bg-emerald-500' : 'bg-red-500' ?>"></div>
                <?= htmlspecialchars($message) ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filters Section -->
        <div class="px-8 pb-6">
            <div class="bg-slate-50/50 p-5 rounded-[2rem] border border-slate-100">
                <form @submit.prevent="applyFilters()" class="grid grid-cols-12 gap-5 items-end">
                    
                    <div class="col-span-12 md:col-span-3 relative">
                        <label class="text-[10px] font-black text-slate-500 uppercase mb-2 block ml-1 tracking-wider">Client</label>
                        <div class="relative">
                            <input type="text" x-model="clientSearch" @input="handleClientInput" placeholder="Search client..." class="w-full border-white rounded-2xl p-3 bg-white text-sm font-bold shadow-sm outline-none focus:ring-4 focus:ring-red-500/10 transition-all">
                            <div x-show="showClientSuggestions" class="absolute z-[60] w-full bg-white border border-slate-100 mt-2 rounded-2xl shadow-2xl max-h-48 overflow-y-auto">
                                <template x-for="c in filteredClients" :key="c">
                                    <div @click="selectClient(c)" class="p-3 text-xs font-bold text-slate-600 hover:bg-red-50 cursor-pointer border-b border-slate-50 transition-colors" x-text="c"></div>
                                </template>
                            </div>
                        </div>
                    </div>

                    <div class="col-span-12 md:col-span-2 relative">
                        <label class="text-[10px] font-black text-slate-500 uppercase mb-2 block ml-1 tracking-wider">Assigned To</label>
                        <input type="text" x-model="assigneeSearch" @input="handleAssigneeInput" placeholder="Team member..." class="w-full border-white rounded-2xl p-3 bg-white text-sm font-bold shadow-sm outline-none focus:ring-4 focus:ring-red-500/10 transition-all">
                        <div x-show="showAssigneeSuggestions" class="absolute z-[60] w-full bg-white border border-slate-100 mt-2 rounded-2xl shadow-2xl max-h-48 overflow-y-auto">
                            <template x-for="a in filteredStaff" :key="a">
                                <div @click="selectAssignee(a)" class="p-3 text-xs font-bold text-slate-600 hover:bg-red-50 cursor-pointer border-b border-slate-50 transition-colors" x-text="a"></div>
                            </template>
                        </div>
                    </div>

                    <div class="col-span-12 md:col-span-2">
                        <label class="text-[10px] font-black text-slate-500 uppercase mb-2 block ml-1 tracking-wider">Reviewer</label>
                        <select x-model="reviewerId" class="w-full border-white rounded-2xl p-3 bg-white text-sm font-bold shadow-sm outline-none focus:ring-4 focus:ring-red-500/10 transition-all appearance-none cursor-pointer">
                            <option value="all">All Reviewers</option>
                            <?php foreach($reviewers_list as $r): ?>
                                <option value="<?= $r['id'] ?>"><?= $r['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-span-12 md:col-span-3 grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-[10px] font-black text-slate-500 uppercase mb-2 block ml-1 tracking-wider">From Date</label>
                            <input type="date" x-model="startDate" class="w-full border-white rounded-2xl p-3 bg-white text-xs font-bold shadow-sm outline-none focus:ring-4 focus:ring-red-500/10 transition-all">
                        </div>
                        <div>
                            <label class="text-[10px] font-black text-slate-500 uppercase mb-2 block ml-1 tracking-wider">To Date</label>
                            <input type="date" x-model="endDate" class="w-full border-white rounded-2xl p-3 bg-white text-xs font-bold shadow-sm outline-none focus:ring-4 focus:ring-red-500/10 transition-all">
                        </div>
                    </div>

                    <div class="col-span-12 md:col-span-2">
                        <button type="submit" class="w-full bg-slate-900 text-white font-black py-3.5 rounded-2xl text-[11px] uppercase tracking-widest hover:bg-red-600 transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2">
                            <span>Filter</span>
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" /></svg>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Main List Section -->
    <main class="flex-1 overflow-y-auto custom-scroll p-8 pt-6">
        <div class="max-w-7xl mx-auto space-y-6">
            
            <!-- Empty State -->
            <template x-if="tasks.length === 0 && !isLoading">
                <div class="text-center py-32 bg-white rounded-[3rem] border border-dashed border-slate-200 shadow-inner">
                    <div class="w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-6">
                        <svg class="w-10 h-10 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" /></svg>
                    </div>
                    <p class="text-slate-400 font-black uppercase tracking-widest text-sm">No assignments found in vault</p>
                    <p class="text-xs text-slate-300 mt-2 font-bold italic">Try adjusting your filters or date range</p>
                </div>
            </template>

            <!-- Task Cards -->
            <template x-for="task in tasks" :key="task.id">
                <div class="vault-card bg-white p-8 rounded-[2.5rem] border border-slate-100 group shadow-sm">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-10">
                        
                        <div class="flex-1">
                            <div class="flex items-center gap-3 mb-4">
                                <span class="px-3 py-1 bg-red-600 text-white text-[9px] font-black uppercase rounded-full tracking-tighter shadow-md shadow-red-100">Skipped</span>
                                <div class="flex flex-col">
                                    <p class="text-sm font-black text-slate-900 uppercase tracking-tight" x-text="task.client_name"></p>
                                    <p class="text-[10px] text-slate-400 font-bold" x-text="`Task ID: #${task.id}`"></p>
                                </div>
                            </div>
                            
                            <h4 class="text-lg font-extrabold text-slate-700 leading-tight mb-4 group-hover:text-red-600 transition-colors" x-text="task.title"></h4>
                            
                            <!-- Reason Box -->
                            <div class="p-4 bg-slate-50 rounded-3xl border border-slate-100 group-hover:bg-red-50/50 group-hover:border-red-100 transition-all">
                                <div class="flex items-center gap-2 mb-2">
                                    <svg class="w-3.5 h-3.5 text-red-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" /></svg>
                                    <p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Reason for Skip</p>
                                </div>
                                <p class="text-sm font-bold text-slate-600 italic leading-relaxed" x-text="task.skip_reason || 'No specific reason documented in logs'"></p>
                            </div>
                        </div>

                        <!-- Divider -->
                        <div class="flex-none w-px h-24 bg-slate-100 hidden md:block group-hover:bg-red-100 transition-colors"></div>

                        <!-- Meta Info -->
                        <div class="md:w-56 space-y-4">
                            <div>
                                <p class="text-[10px] font-black text-slate-300 uppercase tracking-widest mb-2">Assigned Personnel</p>
                                <div class="flex items-center gap-2">
                                    <div class="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-[10px] font-black text-slate-400 border border-slate-200" x-text="task.assignee_name.charAt(0)"></div>
                                    <div>
                                        <p class="text-xs font-black text-slate-800" x-text="task.assignee_name"></p>
                                        <p class="text-[10px] font-bold text-slate-400" x-text="`Rev: ${task.reviewer_name || 'System'}`"></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <p class="text-[10px] font-black text-slate-300 uppercase tracking-widest mb-1">Assignment Date</p>
                                <div class="flex items-center gap-1.5 text-slate-600">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                                    <p class="text-xs font-black" x-text="task.assigned_date"></p>
                                </div>
                            </div>
                        </div>

                        <!-- Action Button -->
                        <div class="flex-none w-full md:w-auto">
                            <form method="POST" @submit="return confirm('Do you want to restore this task to Active Flow? Date will remain unchanged.')">
                                <input type="hidden" name="task_id" :value="task.id">
                                <button type="submit" name="restore_task" class="w-full md:w-auto px-8 py-4 bg-emerald-50 text-emerald-600 rounded-[1.5rem] font-black text-xs uppercase hover:bg-emerald-600 hover:text-white transition-all shadow-sm border border-emerald-100 flex items-center justify-center gap-2 group/btn">
                                    <svg class="w-4 h-4 group-hover/btn:rotate-180 transition-transform duration-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                                    <span>Restore Task</span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </template>

            <!-- Loading Spinnner -->
            <div x-show="isLoading" class="text-center py-10">
                <div class="inline-block animate-spin rounded-full h-10 w-10 border-[3px] border-slate-200 border-t-red-600"></div>
            </div>
            
            <!-- Intersection Trigger -->
            <div x-show="tasks.length > 0 && !noMoreData" x-intersect="loadMoreTasks()" class="h-10"></div>
            
            <!-- End Footer -->
            <p x-show="noMoreData && tasks.length > 0" class="text-center text-slate-300 font-bold uppercase text-[10px] py-16 tracking-[0.6em]">--- END OF VAULT ARCHIVE ---</p>
        </div>
    </main>
</div>

<script>
function skippedTasksHandler() {
    return {
        tasks: [],
        clients: <?= json_encode(array_column($all_clients, 'name')) ?>,
        staff: <?= json_encode(array_column($all_staff, 'name')) ?>,
        filteredClients: [],
        filteredStaff: [],
        clientSearch: '',
        assigneeSearch: '',
        reviewerId: 'all',
        startDate: '<?= date('Y-m-d', strtotime("-45 days")) ?>',
        endDate: '<?= date('Y-m-d') ?>',
        page: 1,
        isLoading: false,
        noMoreData: false,
        showClientSuggestions: false,
        showAssigneeSuggestions: false,

        init() {
            this.loadMoreTasks();
        },

        handleClientInput() {
            if (this.clientSearch.length >= 2) {
                this.filteredClients = this.clients.filter(c => c.toLowerCase().includes(this.clientSearch.toLowerCase()));
                this.showClientSuggestions = this.filteredClients.length > 0;
            } else { this.showClientSuggestions = false; }
        },
        selectClient(name) { this.clientSearch = name; this.showClientSuggestions = false; this.applyFilters(); },

        handleAssigneeInput() {
            if (this.assigneeSearch.length >= 2) {
                this.filteredStaff = this.staff.filter(s => s.toLowerCase().includes(this.assigneeSearch.toLowerCase()));
                this.showAssigneeSuggestions = this.filteredStaff.length > 0;
            } else { this.showAssigneeSuggestions = false; }
        },
        selectAssignee(name) { this.assigneeSearch = name; this.showAssigneeSuggestions = false; this.applyFilters(); },

        applyFilters() { 
            this.tasks = []; 
            this.page = 1; 
            this.noMoreData = false; 
            this.loadMoreTasks(); 
        },

        loadMoreTasks() {
            if (this.isLoading || this.noMoreData) return;
            this.isLoading = true;
            
            let url = `skipped_tasks.php?fetch_ajax=1&page=${this.page}&client_search=${encodeURIComponent(this.clientSearch)}&assignee_search=${encodeURIComponent(this.assigneeSearch)}&reviewer_id=${this.reviewerId}&start_date=${this.startDate}&end_date=${this.endDate}`;
            
            fetch(url)
                .then(res => res.json())
                .then(data => {
                    if (data.length < 10) this.noMoreData = true;
                    this.tasks = [...this.tasks, ...data];
                    this.page++;
                    this.isLoading = false;
                })
                .catch(err => {
                    console.error("Vault fetch error:", err);
                    this.isLoading = false;
                });
        }
    }
}
</script>

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