<?php
// config.php को शामिल करें, जो सेशन और डेटाबेस कनेक्शन को संभालेगा।
require_once 'config.php';

// यह फंक्शन जांच करेगा कि मौजूदा यूजर एडमिन या मैनेजर है या नहीं।
function userHasRole($required_roles) {
    if (!isset($_SESSION['user_roles'])) return false;
    return count(array_intersect($required_roles, $_SESSION['user_roles'])) > 0;
}

// सुरक्षा जांच: केवल एडमिन और मैनेजर ही इस पेज को देख सकते हैं।
if (!isset($_SESSION['user_id']) || !userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}
$is_admin_or_manager = userHasRole(['Admin', 'Manager']);
$is_smm = userHasRole(['SMM']);

$message = '';
$message_type = '';

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_POST['user_id'];
    $report_date = $_POST['report_date'];
    $attendance = $_POST['attendance'];

    // अगर उपस्थिति 'Present' नहीं है, तो टास्क वैल्यू को NULL पर सेट करें
    $total_assigned = ($attendance == 'Present') ? $_POST['total_assigned'] : NULL;
    $total_done = ($attendance == 'Present') ? $_POST['total_done'] : NULL;
    $additional_assigned = ($attendance == 'Present') ? $_POST['additional_assigned'] : NULL;
    $additional_done = ($attendance == 'Present') ? $_POST['additional_done'] : NULL;
    $pending_yesterday = ($attendance == 'Present') ? $_POST['pending_yesterday'] : NULL;


    $stmt = $conn->prepare("INSERT INTO daily_reports (user_id, report_date, attendance, total_assigned_tasks, total_done_tasks, additional_assigned_tasks, additional_done_tasks, pending_tasks_yesterday) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE attendance=VALUES(attendance), total_assigned_tasks=VALUES(total_assigned_tasks), total_done_tasks=VALUES(total_done_tasks), additional_assigned_tasks=VALUES(additional_assigned_tasks), additional_done_tasks=VALUES(additional_done_tasks), pending_tasks_yesterday=VALUES(pending_tasks_yesterday)");
    $stmt->bind_param("issiiiii", $user_id, $report_date, $attendance, $total_assigned, $total_done, $additional_assigned, $additional_done, $pending_yesterday);

    if ($stmt->execute()) {
        $message = "Daily report added/updated successfully!";
        $message_type = 'success';
    } else {
        $message = "Error: " . $stmt->error;
        $message_type = 'error';
    }
    $stmt->close();
}

// --- DATA FETCHING for user dropdown ---
$users_result = $conn->query("SELECT id, 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 != 'Admin' GROUP BY u.id ORDER BY name ASC");
$users = [];
while ($row = $users_result->fetch_assoc()) {
    $users[] = $row;
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Daily Report - Digify OS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body class="bg-gray-100">

    <div class="flex flex-col md:flex-row min-h-screen" x-data="{ sidebarOpen: false }">
        
        <div :class="{'translate-x-0': sidebarOpen, '-translate-x-full': !sidebarOpen}" class="w-64 bg-gray-800 text-white p-4 fixed inset-y-0 left-0 transform md:relative md:translate-x-0 transition-transform duration-200 ease-in-out z-30">
            <h1 class="text-2xl font-bold mb-10">Digify OS</h1>
            <nav>
                <a href="my_tasks.php" class="flex items-center gap-3 py-2.5 px-4 rounded hover:bg-gray-700">My Tasks</a>
                <a href="employee-profile.php?id=<?php echo $_SESSION['user_id']; ?>" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">My Profile</a>
                
                <?php if (userHasRole(['SMM', 'Admin', 'Manager'])): ?>
                    <a href="review_tasks.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Review Tasks</a>
                <?php endif; ?>

                <?php if ($is_admin_or_manager): ?>
                    <div class="mt-4 pt-4 border-t border-gray-700">
                        <h3 class="px-4 text-xs font-semibold text-gray-400 uppercase tracking-wider">Admin Tools</h3>
                        <a href="dashboard.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Admin Dashboard</a>
                        <a href="master_task_flow.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Task Flow</a>
                        <a href="skipped_tasks.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Skipped Tasks</a>
                        <a href="clients.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Clients</a>
                        <a href="employees.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Employees</a>
                        <a href="reports.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Reports</a>
                        <a href="leave-management.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Leave Management</a>
                    </div>
                <?php endif; ?>

                <div class="mt-4 pt-4 border-t border-gray-700">
                    <a href="leave-request.php" class="flex items-center gap-3 py-2.5 px-4 rounded hover:bg-gray-700">Leave Request</a>
                    <a href="change-password.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Change Password</a>
                    <a href="logout.php" class="flex items-center gap-3 mt-2 py-2.5 px-4 rounded hover:bg-gray-700">Logout</a>
                </div>
            </nav>
        </div>
        <div class="flex-1">
            <header class="bg-white shadow-sm p-4 flex justify-between items-center">
                 <button class="md:hidden" @click.stop="sidebarOpen = !sidebarOpen">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /></svg>
                </button>
                <h2 class="text-xl font-bold text-gray-800">Add Daily Report</h2>
                <div class="text-sm"><?php echo htmlspecialchars($_SESSION['user_name']); ?></div>
            </header>

            <main class="p-6 md:p-10">
                <div class="max-w-3xl mx-auto bg-white p-8 rounded-lg shadow">
                    <?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; ?>

                    <form method="POST" action="add-report.php">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-4">
                            <div>
                                <label for="user_id" class="block text-sm font-medium text-gray-700">Employee</label>
                                <select name="user_id" id="user_id" required class="mt-1 block w-full px-3 py-2 border bg-white border-gray-300 rounded-md shadow-sm">
                                    <option value="">-- Select Employee --</option>
                                    <?php foreach ($users as $user): ?>
                                        <option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label for="report_date" class="block text-sm font-medium text-gray-700">Date</label>
                                <input type="date" name="report_date" id="report_date" value="<?php echo date('Y-m-d'); ?>" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                            </div>
                            <div>
                                <label for="attendance" class="block text-sm font-medium text-gray-700">Attendance</label>
                                <select name="attendance" id="attendance" required class="mt-1 block w-full px-3 py-2 border bg-white border-gray-300 rounded-md shadow-sm">
                                    <option value="Present">Present</option>
                                    <option value="CL">CL</option>
                                    <option value="Absent">Absent</option>
                                </select>
                            </div>
                        </div>

                        <div id="task-details" class="space-y-4 border-t border-gray-200 pt-6 mt-6">
                            <div class="grid grid-cols-2 gap-6">
                                <div>
                                    <label for="total_assigned" class="block text-sm font-medium text-gray-700">Total Assigned Tasks</label>
                                    <input type="number" name="total_assigned" id="total_assigned" value="0" min="0" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                                </div>
                                <div>
                                    <label for="total_done" class="block text-sm font-medium text-gray-700">Total Done Tasks</label>
                                    <input type="number" name="total_done" id="total_done" value="0" min="0" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-6">
                                <div>
                                    <label for="additional_assigned" class="block text-sm font-medium text-gray-700">Additional Assigned</label>
                                    <input type="number" name="additional_assigned" id="additional_assigned" value="0" min="0" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                                </div>
                                <div>
                                    <label for="additional_done" class="block text-sm font-medium text-gray-700">Additional Done</label>
                                    <input type="number" name="additional_done" id="additional_done" value="0" min="0" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                                </div>
                            </div>
                             <div class="grid grid-cols-2 gap-6">
                                <div>
                                    <label for="pending_yesterday" class="block text-sm font-medium text-gray-700">Pending from Yesterday</label>
                                    <input type="number" name="pending_yesterday" id="pending_yesterday" value="0" min="0" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end mt-6">
                            <button type="submit" class="inline-flex items-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-white hover:bg-blue-700">
                                Save Report
                            </button>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>

    <script>
        const attendanceSelect = document.getElementById('attendance');
        const taskDetailsDiv = document.getElementById('task-details');

        // टास्क विवरण की दृश्यता को टॉगल करने के लिए फंक्शन
        function toggleTaskDetails() {
            if (attendanceSelect.value === 'Present') {
                taskDetailsDiv.style.display = 'block';
            } else {
                taskDetailsDiv.style.display = 'none';
            }
        }

        // ड्रॉपडाउन में इवेंट लिस्नर जोड़ें
        attendanceSelect.addEventListener('change', toggleTaskDetails);

        // प्रारंभिक स्थिति सेट करने के लिए पेज लोड पर चलाएं
        toggleTaskDetails();
    </script>

</body>
</html>