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

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

$user_id = $_SESSION['user_id'];
$canChangeReviewer = userHasRole(['Admin', 'Sales']);
$isAdminOrManager = userHasRole(['Admin', 'Manager']);

// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
$generation_log = $_SESSION['generation_log'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type'], $_SESSION['generation_log']);

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // 1. Reviewer Update Logic (Admin/Sales)
    if (isset($_POST['change_all_reviewers']) && $canChangeReviewer) {
        $new_rev_id = (int)$_POST['global_reviewer_id'];
        if ($new_rev_id > 0) {
            $conn->query("UPDATE tasks SET smm_user_id = $new_rev_id WHERE work_type = 'Report' AND status IN ('Not Started', 'In Process', 'Rejected')");
            $_SESSION['message'] = "Global reviewer updated.";
            $_SESSION['message_type'] = 'success';
        }
    }
    
    // 2. Report Submit Logic
    elseif (isset($_POST['submit_report'])) {
        $task_id = (int)$_POST['task_id'];
        $client_id = (int)$_POST['client_id'];
        $report_date = date('Y-m-d');
        
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("INSERT INTO client_reports (client_id, report_date, google_reviews, instagram_followers, posts_count, reels_count, created_by_user_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isiiiii", $client_id, $report_date, $_POST['google_reviews'], $_POST['instagram_followers'], $_POST['posts_count'], $_POST['reels_count'], $user_id);
            $stmt->execute();
            
            $conn->query("UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE id = $task_id");
            
            $conn->commit();
            $_SESSION['message'] = "Report submitted successfully!";
            $_SESSION['message_type'] = 'success';
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['message'] = "Error: " . $e->getMessage();
            $_SESSION['message_type'] = 'error';
        }
    }
    
    // 3. Task Generation Logic
    elseif (isset($_POST['generate_reports']) && $isAdminOrManager) {
        ob_start();
        include 'create_report_tasks.php'; 
        $_SESSION['generation_log'] = ob_get_clean(); 
        $_SESSION['message'] = "Report generation script executed.";
        $_SESSION['message_type'] = 'success';
    }
    
    header("Location: pending_reports.php");
    exit();
}

// --- DATA FETCHING ---

// Filter Dropdown: Analyst + Manager permissions
$reviewer_list = $conn->query("SELECT DISTINCT u.id, u.name FROM users u 
    JOIN user_roles ur1 ON u.id = ur1.user_id JOIN roles r1 ON ur1.role_id = r1.id 
    JOIN user_roles ur2 ON u.id = ur2.user_id JOIN roles r2 ON ur2.role_id = r2.id 
    WHERE r1.name = 'Analyst' AND r2.name = 'Manager' 
    ORDER BY u.name ASC")->fetch_all(MYSQLI_ASSOC);

$all_clients = $conn->query("SELECT name FROM clients WHERE is_active = TRUE ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

// Filters
$client_search = $_GET['client_search'] ?? '';
$user_filter_id = $_GET['user_id'] ?? 'all';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$sql = "SELECT t.*, c.name as client_name, u.name as assigned_user_name 
        FROM tasks t
        JOIN clients c ON t.client_id = c.id
        JOIN users u ON t.assigned_user_id = u.id
        WHERE t.work_type = 'Report'
        AND t.status IN ('Not Started', 'In Process', 'Rejected')";

// Privacy Filter
if (!userHasRole(['Admin', 'Manager', 'Sales'])) {
    $sql .= " AND t.assigned_user_id = $user_id";
}

$params = [];
$types = "";

if ($client_search != '') { $sql .= " AND c.name LIKE ?"; $params[] = "%$client_search%"; $types .= "s"; }
if ($user_filter_id != 'all') { $sql .= " AND t.assigned_user_id = ?"; $params[] = $user_filter_id; $types .= "i"; }
if ($start_date != '') { $sql .= " AND t.assigned_date >= ?"; $params[] = $start_date; $types .= "s"; }
if ($end_date != '') { $sql .= " AND t.assigned_date <= ?"; $params[] = $end_date; $types .= "s"; }

$sql .= " ORDER BY t.assigned_date ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$report_tasks = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

require_once 'header.php';
?>

<title>Pending Reports - Digify OS</title>
<div class="flex-1" x-data="{ isReportModalOpen: false, isGenerateModalOpen: false, currentTask: {} }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center border-b">
        <h2 class="text-xl font-bold text-gray-800">Pending 10-Day Reports</h2>
        <?php if($isAdminOrManager): ?>
        <button @click="isGenerateModalOpen = true" class="px-4 py-2 bg-green-600 text-white text-[10px] font-black rounded-lg hover:bg-green-700 uppercase">Generate Tasks</button>
        <?php endif; ?>
    </header>

    <main class="p-6">
        
        <?php if ($canChangeReviewer): ?>
        <div class="bg-indigo-50 p-5 rounded-2xl border border-indigo-100 mb-8 flex flex-col md:flex-row justify-between items-center gap-4 shadow-sm">
            <div>
                <h4 class="text-indigo-900 font-black text-sm uppercase italic">Reviewer Management</h4>
                <p class="text-indigo-600 text-[10px] font-bold uppercase tracking-tight">Assign a global reviewer for all pending tasks.</p>
            </div>
            <form method="POST" class="flex items-center gap-3">
                <select name="global_reviewer_id" required class="w-64 border-gray-200 rounded-xl text-sm p-2 shadow-inner">
                    <option value="">Select Analyst Manager</option>
                    <?php foreach($reviewer_list as $rev): ?>
                        <option value="<?= $rev['id'] ?>"><?= htmlspecialchars($rev['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" name="change_all_reviewers" class="px-5 py-2 bg-indigo-600 text-white text-[10px] font-black rounded-xl hover:bg-indigo-700 uppercase transition">Update</button>
            </form>
        </div>
        <?php endif; ?>

        <?php if (!empty($message)): ?>
            <div class="mb-4 p-4 rounded-xl <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?> font-bold text-sm">
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>

        <div class="bg-white p-6 rounded-2xl shadow-sm border mb-8">
            <form method="GET" action="pending_reports.php" class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                
                <div>
                    <label class="text-[10px] font-bold text-gray-400 uppercase mb-1 block">Client Name</label>
                    <input list="clientSuggestions" name="client_search" value="<?= htmlspecialchars($client_search) ?>" 
                           placeholder="Type to search..." autocomplete="off"
                           class="w-full border-gray-200 rounded-xl text-sm p-3 bg-gray-50 focus:ring-2 focus:ring-blue-500">
                    <datalist id="clientSuggestions">
                        <?php foreach($all_clients as $c): ?>
                            <option value="<?= htmlspecialchars($c['name']) ?>">
                        <?php endforeach; ?>
                    </datalist>
                </div>

                <div>
                    <label class="text-[10px] font-bold text-gray-400 uppercase mb-1 block">Assigned Analyst</label>
                    <select name="user_id" class="w-full border-gray-200 rounded-xl text-sm p-3 bg-gray-50">
                        <option value="all">All Managers</option>
                        <?php foreach($reviewer_list as $u): ?>
                            <option value="<?= $u['id'] ?>" <?= ($user_filter_id == $u['id']) ? 'selected' : '' ?>><?= htmlspecialchars($u['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] font-bold text-gray-400 uppercase mb-1 block">From Date</label>
                    <input type="date" name="start_date" value="<?= $start_date ?>" class="w-full border-gray-200 rounded-xl text-sm p-3 bg-gray-50">
                </div>
                <div>
                    <label class="text-[10px] font-bold text-gray-400 uppercase mb-1 block">To Date</label>
                    <input type="date" name="end_date" value="<?= $end_date ?>" class="w-full border-gray-200 rounded-xl text-sm p-3 bg-gray-50">
                </div>

                <div class="flex gap-2">
                    <button type="submit" class="flex-1 bg-blue-600 text-white font-black py-3 rounded-xl text-[10px] uppercase tracking-widest hover:bg-blue-700 shadow-lg transition">Filter</button>
                    <a href="pending_reports.php" class="bg-gray-100 text-gray-400 px-4 py-3 rounded-xl hover:bg-gray-200 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                    </a>
                </div>
            </form>
        </div>

        <div class="grid grid-cols-1 gap-4">
            <?php if (empty($report_tasks)): ?>
                <div class="bg-white p-12 rounded-3xl text-center border-2 border-dashed border-gray-100">
                    <p class="text-gray-400 font-bold uppercase tracking-widest text-[10px]">No pending data found</p>
                </div>
            <?php else: ?>
                <?php foreach ($report_tasks as $task): ?>
                    <div class="bg-white rounded-2xl shadow-sm p-6 flex justify-between items-center border border-gray-50 hover:border-blue-200 transition-all group">
                        <div>
                            <p class="font-black text-gray-900 text-lg tracking-tight group-hover:text-blue-600"><?= htmlspecialchars($task['title']) ?></p>
                            <p class="text-[10px] font-bold text-gray-400 uppercase mt-1">
                                BY: <span class="text-indigo-600"><?= htmlspecialchars($task['assigned_user_name']) ?></span> 
                                <span class="mx-2">|</span> DATE: <span class="text-gray-600"><?= date("d M, Y", strtotime($task['assigned_date'])) ?></span>
                            </p>
                        </div>
                        <button @click="isReportModalOpen = true; currentTask = <?= htmlspecialchars(json_encode($task)) ?>" 
                                class="px-8 py-3 bg-blue-600 text-white text-[10px] font-black rounded-xl hover:bg-blue-700 shadow-lg transition uppercase tracking-widest">
                            Enter Data
                        </button>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </main>

    <div x-show="isReportModalOpen" class="fixed inset-0 bg-black bg-opacity-60 backdrop-blur-sm flex items-center justify-center z-50 p-4" style="display:none;">
        <div class="bg-white rounded-3xl shadow-2xl p-8 w-full max-w-2xl" @click.away="isReportModalOpen = false">
            <h3 class="text-2xl font-black mb-1 text-gray-800 uppercase tracking-tighter">Report Data</h3>
            <p class="text-xs font-bold text-gray-400 uppercase mb-8 border-b pb-4">Client: <span x-text="currentTask.client_name" class="text-blue-600"></span></p>
            <form method="POST" class="space-y-4">
                <input type="hidden" name="task_id" :value="currentTask.id">
                <input type="hidden" name="client_id" :value="currentTask.client_id">
                <div class="grid grid-cols-2 gap-6">
                    <div><label class="block text-[10px] font-black uppercase text-gray-400 mb-2">Google Reviews</label><input type="number" name="google_reviews" required class="w-full border-gray-200 rounded-2xl p-4 bg-gray-50 focus:ring-2 focus:ring-blue-500 transition"></div>
                    <div><label class="block text-[10px] font-black uppercase text-gray-400 mb-2">Insta Followers</label><input type="number" name="instagram_followers" required class="w-full border-gray-200 rounded-2xl p-4 bg-gray-50 focus:ring-2 focus:ring-blue-500 transition"></div>
                    <div><label class="block text-[10px] font-black uppercase text-gray-400 mb-2">Posts count</label><input type="number" name="posts_count" required class="w-full border-gray-200 rounded-2xl p-4 bg-gray-50 focus:ring-2 focus:ring-blue-500 transition"></div>
                    <div><label class="block text-[10px] font-black uppercase text-gray-400 mb-2">Reels count</label><input type="number" name="reels_count" required class="w-full border-gray-200 rounded-2xl p-4 bg-gray-50 focus:ring-2 focus:ring-blue-500 transition"></div>
                </div>
                <div class="flex justify-end gap-3 pt-6">
                    <button type="button" @click="isReportModalOpen = false" class="px-6 py-3 border rounded-2xl font-black text-[10px] uppercase text-gray-400">Cancel</button>
                    <button type="submit" name="submit_report" class="px-10 py-3 bg-blue-600 text-white font-black rounded-2xl hover:bg-blue-700 shadow-xl text-[10px] uppercase tracking-widest transition">Submit & Finish</button>
                </div>
            </form>
        </div>
    </div>

    <div x-show="isGenerateModalOpen" class="fixed inset-0 bg-black bg-opacity-60 backdrop-blur-sm flex items-center justify-center z-50 p-4" style="display:none;">
        <div class="bg-white rounded-3xl p-8 max-w-md w-full shadow-2xl text-center">
            <h3 class="text-xl font-black mb-4 uppercase italic">Run System Generation?</h3>
            <p class="text-xs font-bold text-gray-400 mb-8 leading-relaxed uppercase">This will scan all clients and create tasks for those due for a 10-day report. System start date (Jan 15) applies.</p>
            <form method="POST" class="flex justify-center gap-4">
                <button type="button" @click="isGenerateModalOpen = false" class="px-6 py-3 bg-gray-100 rounded-2xl font-black text-[10px] uppercase">Cancel</button>
                <button type="submit" name="generate_reports" class="px-8 py-3 bg-green-600 text-white font-black rounded-2xl shadow-lg text-[10px] uppercase">Run Generation</button>
            </form>
        </div>
    </div>

</div>

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