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

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

// --- फिल्टर्स aur Pagination ---
$limit = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$start_date_str = $_GET['start_date'] ?? date('Y-m-01');
$end_date_str = $_GET['end_date'] ?? date('Y-m-t');
$selected_employee_id = $_GET['employee_id'] ?? 'all';

// --- DATA FETCHING ---
$params = [];
$param_types = '';

// Pagination ke liye कुल records
$count_sql = "SELECT COUNT(DISTINCT u.id, DATE(t.completed_at)) 
              FROM tasks t JOIN users u ON t.assigned_user_id = u.id 
              WHERE t.status = 'Completed' AND t.completed_at BETWEEN ? AND ?";
$count_params = [$start_date_str . ' 00:00:00', $end_date_str . ' 23:59:59'];
$count_param_types = 'ss';

if ($selected_employee_id !== 'all') {
    $count_sql .= " AND u.id = ?";
    $count_params[] = $selected_employee_id;
    $count_param_types .= 'i';
}

$count_stmt = $conn->prepare($count_sql);
$count_stmt->bind_param($count_param_types, ...$count_params);
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_row()[0];
$total_pages = ceil($total_records / $limit);
$count_stmt->close();


// Reports ka data fetch karein
$sql = "SELECT 
            u.id as user_id, 
            u.name,
            u.daily_target,
            DATE(t.completed_at) as report_date,
            COUNT(t.id) as total_completed,
            SUM(CASE WHEN t.task_type = 'Regular' THEN 1 ELSE 0 END) as regular_completed,
            SUM(CASE WHEN t.task_type = 'Additional' THEN 1 ELSE 0 END) as additional_completed,
            (SELECT COUNT(*) FROM tasks r WHERE r.assigned_user_id = u.id AND DATE(r.completed_at) = DATE(t.completed_at) AND r.rejection_count > 0) as total_rejected
        FROM tasks t
        JOIN users u ON t.assigned_user_id = u.id
        WHERE t.status = 'Completed' AND t.completed_at BETWEEN ? AND ?";

$params = [$start_date_str . ' 00:00:00', $end_date_str . ' 23:59:59'];
$param_types = 'ss';

if ($selected_employee_id !== 'all') {
    $sql .= " AND u.id = ?";
    $params[] = $selected_employee_id;
    $param_types .= 'i';
}

$sql .= " GROUP BY u.id, report_date ORDER BY report_date DESC, u.name ASC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$processed_reports = [];
while ($row = $result->fetch_assoc()) {
    $target = $row['daily_target'] > 0 ? $row['daily_target'] : 1;
    $row['production'] = round(($row['total_completed'] / $target) * 100, 1);
    $row['quality'] = $row['total_completed'] > 0 ? round((($row['total_completed'] - $row['total_rejected']) / $row['total_completed']) * 100, 1) : 100;
    $row['rating'] = min(5, round(($row['total_completed'] / $target) * 5, 2));
    $processed_reports[] = $row;
}
$stmt->close();

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

require_once 'header.php';
?>

<title>Automatic Reports - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Automatic Performance Reports</h2>

<main class="p-6 md:p-10">
    <div class="bg-white p-4 rounded-lg shadow-md mb-8 sticky top-0 z-10">
        <form method="GET" action="reports.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_str); ?>" 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_str); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">Employee</label>
                    <select name="employee_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All Employees</option>
                        <?php foreach($all_employees as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>" <?php if($selected_employee_id == $emp['id']) echo 'selected'; ?>><?php echo htmlspecialchars($emp['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="reports.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="bg-white rounded-lg shadow-lg overflow-hidden">
        <div class="overflow-y-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Date</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Employee</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Completed (Reg+Add)</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Production</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Quality</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Rating</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($processed_reports)): ?>
                        <tr><td colspan="6" class="px-6 py-10 text-center text-gray-500">No completed tasks found for this period.</td></tr>
                    <?php else: ?>
                        <?php foreach ($processed_reports as $report): ?>
                            <tr>
                                <td class="px-6 py-4"><?php echo date("d M, Y", strtotime($report['report_date'])); ?></td>
                                <td class="px-6 py-4 font-semibold"><?php echo htmlspecialchars($report['name']); ?></td>
                                <td class="px-6 py-4"><?php echo $report['total_completed']; ?> (<?php echo $report['regular_completed']; ?> + <?php echo $report['additional_completed']; ?>)</td>
                                <td class="px-6 py-4 font-bold"><?php echo $report['production']; ?>%</td>
                                <td class="px-6 py-4 font-bold"><?php echo $report['quality']; ?>%</td>
                                <td class="px-6 py-4 font-bold"><?php echo $report['rating']; ?> / 5</td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php if ($total_pages > 1): ?>
        <div class="p-4 flex justify-between items-center">
            <span class="text-sm text-gray-700">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </span>
            <div class="space-x-2">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&start_date=<?php echo $start_date_str; ?>&end_date=<?php echo $end_date_str; ?>&employee_id=<?php echo $selected_employee_id; ?>" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm">&laquo; Previous</a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&start_date=<?php echo $start_date_str; ?>&end_date=<?php echo $end_date_str; ?>&employee_id=<?php echo $selected_employee_id; ?>" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm">Next &raquo;</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

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