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

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

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

// --- AUTO-APPROVAL LOGIC ---
$auto_approve_sql = "UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE status = 'Final Review' AND is_checklist_task = TRUE AND submitted_for_review_at < NOW() - INTERVAL 24 HOUR";
$conn->query($auto_approve_sql);


// --- MANUAL APPROVE/REJECT LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['task_action'])) {
    $task_id = $_POST['task_id'];
    $action = $_POST['task_action'];

    if ($action == 'Approve') {
        $stmt = $conn->prepare("UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE id = ?");
        $stmt->bind_param("i", $task_id);
        if($stmt->execute()){ 
            $_SESSION['message'] = "Task approved successfully!";
            $_SESSION['message_type'] = 'success';
        }
        $stmt->close();
    } elseif ($action == 'Reject') {
        $rejection_reason = $_POST['rejection_reason'];
        $stmt = $conn->prepare("UPDATE tasks SET status = 'Rejected', rejection_reason = ? WHERE id = ?");
        $stmt->bind_param("si", $rejection_reason, $task_id);
        if($stmt->execute()){ 
            $_SESSION['message'] = "Task rejected and sent back to SMM.";
            $_SESSION['message_type'] = 'success';
        }
        $stmt->close();
    }
    
    header("Location: manager_review.php");
    exit();
}


// --- DATA FETCHING ---
$start_date_filter = $_GET['start_date'] ?? '';
$end_date_filter = $_GET['end_date'] ?? '';
$user_filter_id = $_GET['user_id'] ?? 'all';

$sql = "SELECT t.*, c.name as client_name, u.name as smm_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.status = 'Final Review' AND t.is_checklist_task = TRUE"; // **YAHAN PAR MUKHYA BADLAV HAI**

$params = [];
$param_types = '';

if ($user_filter_id != 'all' && is_numeric($user_filter_id)) {
    $sql .= " AND t.assigned_user_id = ?";
    $params[] = $user_filter_id;
    $param_types .= 'i';
}
if (!empty($start_date_filter)) {
    $sql .= " AND DATE(t.submitted_for_review_at) >= ?";
    $params[] = $start_date_filter;
    $param_types .= 's';
}
if (!empty($end_date_filter)) {
    $sql .= " AND DATE(t.submitted_for_review_at) <= ?";
    $params[] = $end_date_filter;
    $param_types .= 's';
}
$sql .= " ORDER BY t.submitted_for_review_at ASC";

$stmt = $conn->prepare($sql);
if(!empty($params)){ $stmt->bind_param($param_types, ...$params); }
$stmt->execute();
$result = $stmt->get_result();
$review_tasks = [];
while ($row = $result->fetch_assoc()) {
    $checklist_stmt = $conn->prepare("SELECT * FROM smm_checklists WHERE task_id = ? AND is_completed = 1");
    $checklist_stmt->bind_param("i", $row['id']);
    $checklist_stmt->execute();
    $row['checklist'] = $checklist_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $checklist_stmt->close();
    $review_tasks[] = $row;
}
$stmt->close();

// Dropdown ke liye users (SMMs)
$users_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 = 'SMM' ORDER BY u.name ASC");
$smm_users = $users_result->fetch_all(MYSQLI_ASSOC);

$conn->close();

// Ab yahan par header.php ko include karein
require_once 'header.php';
?>

<title>Manager Review - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Manager's Final Review</h2>

<main class="p-6 md:p-10">
    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
    <div class="bg-blue-50 border border-blue-200 p-4 rounded-lg mb-6 text-sm text-blue-800">
        <p><span class="font-bold">Note:</span> Tasks that are pending review for more than 24 hours will be automatically approved.</p>
    </div>

    <div class="bg-white p-4 rounded-lg shadow-md mb-8">
        <form method="GET" action="manager_review.php">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                <div><label class="text-sm font-medium text-gray-700">Start Date</label><input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="text-sm font-medium text-gray-700">End Date</label><input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="text-sm font-medium text-gray-700">Submitted By (SMM)</label><select name="user_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="all">All SMMs</option><?php foreach($smm_users as $user): ?><option value="<?php echo $user['id']; ?>" <?php if($user_filter_id == $user['id']) echo 'selected'; ?>><?php echo htmlspecialchars($user['name']); ?></option><?php endforeach; ?></select></div>
                <div class="flex items-center gap-4">
                    <button type="submit" class="w-full px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    <a href="manager_review.php" class="w-full text-center px-6 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300">Reset</a>
                </div>
            </div>
        </form>
    </div>

    <div class="space-y-4">
        <?php if (empty($review_tasks)): ?>
            <div class="bg-white p-8 rounded-lg shadow text-center">
                <h3 class="mt-2 text-lg font-medium text-gray-900">All Clear!</h3>
                <p class="mt-1 text-sm text-gray-500">No tasks are currently waiting for your review.</p>
            </div>
        <?php else: ?>
            <?php foreach ($review_tasks as $task): ?>
                <div class="bg-white rounded-lg shadow-md overflow-hidden transition-shadow duration-300 hover:shadow-xl" x-data="{ isRejectModalOpen: false, currentTask: <?php echo htmlspecialchars(json_encode($task)); ?> }">
                    <div class="p-5 flex flex-col md:flex-row justify-between items-start gap-4">
                        <div class="flex-grow">
                            <p class="text-lg font-bold text-gray-900 mt-1"><?php echo htmlspecialchars($task['title']); ?></p>
                            <p class="text-xs text-gray-500 mt-2">Submitted by <span class="font-semibold"><?php echo htmlspecialchars($task['smm_name']); ?></span> for <span class="font-semibold"><?php echo htmlspecialchars($task['client_name']); ?></span> at <?php echo date("d M, Y h:i A", strtotime($task['submitted_for_review_at'])); ?></p>
                            
                            <div class="mt-3 border-t pt-3">
                                <p class="text-sm font-semibold text-gray-700">Completed Checklist:</p>
                                <ul class="list-disc list-inside text-sm text-gray-600 mt-1">
                                    <?php foreach($task['checklist'] as $item): ?>
                                        <li><?php echo htmlspecialchars($item['item_description']); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                        <div class="flex-shrink-0 flex items-center gap-3 mt-4 md:mt-0">
                            <form method="POST" action="manager_review.php" onsubmit="return confirm('Are you sure you want to approve this task?');">
                                <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                <button type="submit" name="task_action" value="Approve" class="px-4 py-2 bg-green-600 text-white text-xs font-semibold rounded-lg shadow-md hover:bg-green-700">Approve</button>
                            </form>
                            <button @click="isRejectModalOpen = true" class="px-4 py-2 bg-red-600 text-white text-xs font-semibold rounded-lg shadow-md hover:bg-red-700">
                                Reject
                            </button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</main>

<div x-show="isRejectModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" @keydown.escape.window="isRejectModalOpen = false">
    <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-lg" @click.away="isRejectModalOpen = false">
        <h3 class="text-xl font-semibold text-red-800 mb-2">Confirm Rejection</h3>
        <p class="text-sm text-gray-600 mb-6">Please provide a reason for rejecting this task. The SMM will see this note.</p>
        <form method="POST" action="manager_review.php">
            <input type="hidden" name="task_id" :value="currentTask.id">
            <div class="mb-4">
                <label for="rejection_reason" class="block text-sm font-medium text-gray-700">Rejection Reason</label>
                <textarea name="rejection_reason" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></textarea>
            </div>
            <div class="flex justify-end mt-8">
                <button type="button" @click="isRejectModalOpen = false" class="px-4 py-2 border rounded-md">Cancel</button>
                <button type="submit" name="task_action" value="Reject" class="ml-3 px-4 py-2 bg-red-600 text-white rounded-md font-semibold hover:bg-red-700">Reject Task</button>
            </div>
        </form>
    </div>
</div>

</div>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>