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

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

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

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

    if ($action == 'Approve') {
        $conn->begin_transaction();
        try {
            $stmt1 = $conn->prepare("UPDATE tasks SET status = 'Completed', completed_at = NOW() WHERE id = ?");
            $stmt1->bind_param("i", $task_id);
            if(!$stmt1->execute()) { throw new Exception($stmt1->error); }
            $stmt1->close();
            
            $task_info_stmt = $conn->prepare("SELECT client_id, title FROM tasks WHERE id = ?");
            $task_info_stmt->bind_param("i", $task_id);
            $task_info_stmt->execute();
            $task_info = $task_info_stmt->get_result()->fetch_assoc();
            $task_info_stmt->close();

            $new_title = "Publish: " . $task_info['title'];
            $new_task_stmt = $conn->prepare("INSERT INTO tasks (client_id, assigned_user_id, smm_user_id, title, task_type, is_checklist_task, status, priority, assigned_date) VALUES (?, ?, ?, ?, 'Additional', TRUE, 'Not Started', 'High', CURDATE())");
            $new_task_stmt->bind_param("iiss", $task_info['client_id'], $smm_user_id, $smm_user_id, $new_title);
            if(!$new_task_stmt->execute()) { throw new Exception($new_task_stmt->error); }
            $new_task_id = $conn->insert_id;
            $new_task_stmt->close();
            
            $checklist_items = ["Shared in client group", "Posted on Insta/FB", "Profile Review", "Google Review & Update"];
            $checklist_stmt = $conn->prepare("INSERT INTO smm_checklists (task_id, item_description) VALUES (?, ?)");
            foreach ($checklist_items as $item) {
                $checklist_stmt->bind_param("is", $new_task_id, $item);
                if(!$checklist_stmt->execute()) { throw new Exception($checklist_stmt->error); }
            }
            $checklist_stmt->close();

            $conn->commit();
            $_SESSION['message'] = "Task approved! A new checklist task has been created in 'SMM Workspace'.";
            $_SESSION['message_type'] = 'success';
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['message'] = "An error occurred: " . $e->getMessage();
            $_SESSION['message_type'] = 'error';
        }

    } 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 user.";
            $_SESSION['message_type'] = 'success';
        }
        $stmt->close();
    }
    header("Location: review_tasks.php");
    exit();
}

// --- फिल्टर्स ---
$start_date_filter = $_GET['start_date'] ?? '';
$end_date_filter = $_GET['end_date'] ?? '';
$user_filter_id = $_GET['user_id'] ?? 'all';

// --- DATA FETCHING ---
$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.smm_user_id = ? AND t.status = 'In Review' AND t.is_checklist_task = FALSE";

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

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

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$review_tasks = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Dropdown ke liye users
$users_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$all_users = $users_result->fetch_all(MYSQLI_ASSOC);

$conn->close();

require_once 'header.php';
?>

<title>Review Tasks - Digify OS</title>
<div class="flex-1" x-data="{ isRejectModalOpen: false, currentTask: {} }">
    <header class="bg-white shadow-sm p-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">Tasks Awaiting Your Review</h2>
    </header>

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

    <div class="bg-white p-4 rounded-lg shadow-md mb-8 sticky top-0 z-10">
        <form method="GET" action="review_tasks.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</label><select name="user_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm"><option value="all">All Users</option><?php foreach($all_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="review_tasks.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">
                    <div class="p-5">
                        <div class="flex flex-col md:flex-row justify-between items-start gap-4">
                            <div class="flex-grow">
                                <p class="text-sm font-semibold text-gray-500"><?php echo htmlspecialchars($task['client_name']); ?></p>
                                <p class="text-lg font-bold text-gray-900 mt-1"><?php echo htmlspecialchars($task['title']); ?></p>
                            </div>
                            <div class="flex-shrink-0 flex items-center gap-3 mt-4 md:mt-0">
                                <form method="POST" action="review_tasks.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; currentTask = <?php echo htmlspecialchars(json_encode($task)); ?>" 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 class="border-t mt-4 pt-3 flex items-center text-center text-xs text-gray-500">
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Submitted By</strong>
                                <span><?php echo htmlspecialchars($task['assigned_user_name']); ?></span>
                            </div>
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Assigned Date</strong>
                                <span><?php echo date("d M, Y", strtotime($task['assigned_date'])); ?></span>
                            </div>
                            <div class="flex-1">
                                <strong class="block text-gray-600 font-bold">Work Type</strong>
                                <span class="font-semibold text-gray-700"><?php echo htmlspecialchars($task['work_type']); ?></span>
                            </div>
                        </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 user will see this note.</p>
        <form method="POST" action="review_tasks.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';
?>