<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

auth_start_session();
auth_require_role(['admin']);

$title = 'To Do Tasks';

$q = trim((string)($_GET['q'] ?? ''));
$monthParam = trim((string)($_GET['month'] ?? date('Y-m')));
$detailCustomer = trim((string)($_GET['detail_customer'] ?? ''));

$monthDate = DateTimeImmutable::createFromFormat('Y-m', $monthParam) ?: new DateTimeImmutable('first day of this month');
$monthStart = $monthDate->modify('first day of this month');
$monthEnd = $monthDate->modify('last day of this month');

$error = '';
$notice = '';
$rows = [];

function task_status_badge_class(string $status): string
{
    $s = strtolower(trim($status));
    switch ($s) {
        case 'completed':
            return 'bg-green-50 text-green-700 border-green-200';
        case 'accepted':
        case 'started':
            return 'bg-blue-50 text-blue-700 border-blue-200';
        case 'cancelled':
            return 'bg-red-50 text-red-700 border-red-200';
        case 'rescheduled':
        case 'pending':
        case 'assigned':
            return 'bg-amber-50 text-amber-700 border-amber-200';
        default:
            return 'bg-slate-50 text-slate-700 border-slate-200';
    }
}

try {
    $pdo = Database::pdo();

    $statuses = ['pending', 'assigned', 'accepted', 'started'];
    $placeholders = implode(',', array_fill(0, count($statuses), '?'));

    if ($q !== '') {
        $stmt = $pdo->prepare(
            "SELECT task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address
             FROM admin_all_tasks
             WHERE task_status IN ($placeholders)
               AND scheduled_date BETWEEN ? AND ?
               AND (staff_name LIKE ? OR customer_name LIKE ? OR service_name LIKE ?)
             ORDER BY customer_name ASC, scheduled_date ASC, scheduled_time ASC, task_id ASC"
        );
        $like = '%' . $q . '%';
        $stmt->execute([
            ...$statuses,
            $monthStart->format('Y-m-d'),
            $monthEnd->format('Y-m-d'),
            $like,
            $like,
            $like,
        ]);
    } else {
        $stmt = $pdo->prepare(
            "SELECT task_id, scheduled_date, scheduled_time, task_status, staff_name, customer_name, service_name, property_address
             FROM admin_all_tasks
             WHERE task_status IN ($placeholders)
               AND scheduled_date BETWEEN ? AND ?
             ORDER BY customer_name ASC, scheduled_date ASC, scheduled_time ASC, task_id ASC"
        );
        $stmt->execute([
            ...$statuses,
            $monthStart->format('Y-m-d'),
            $monthEnd->format('Y-m-d'),
        ]);
    }

    $rows = $stmt->fetchAll();

    if (!$rows && $q !== '') {
        $notice = 'No tasks found.';
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$tasksByCustomer = [];
foreach ($rows as $r) {
    $cust = trim((string)($r['customer_name'] ?? ''));
    if ($cust === '') {
        $cust = 'Unknown Customer';
    }
    if (!isset($tasksByCustomer[$cust])) {
        $tasksByCustomer[$cust] = [];
    }
    $tasksByCustomer[$cust][] = $r;
}
ksort($tasksByCustomer, SORT_NATURAL | SORT_FLAG_CASE);

$customerSummaries = [];
foreach ($tasksByCustomer as $custName => $custTasks) {
    $pending = 0;
    $inProgress = 0;
    $latestSchedule = '';
    $services = [];
    $staff = [];

    foreach ($custTasks as $t) {
        $status = strtolower(trim((string)($t['task_status'] ?? '')));
        if (in_array($status, ['pending', 'assigned'], true)) {
            $pending++;
        } elseif (in_array($status, ['accepted', 'started'], true)) {
            $inProgress++;
        }

        $schedule = trim((string)($t['scheduled_date'] ?? '') . ' ' . (string)($t['scheduled_time'] ?? ''));
        if ($schedule !== '' && ($latestSchedule === '' || strcmp($schedule, $latestSchedule) > 0)) {
            $latestSchedule = $schedule;
        }

        $svc = trim((string)($t['service_name'] ?? ''));
        if ($svc !== '') {
            $services[$svc] = true;
        }

        $st = trim((string)($t['staff_name'] ?? ''));
        if ($st !== '') {
            $staff[$st] = true;
        }
    }

    $customerSummaries[] = [
        'customer_name' => $custName,
        'task_count' => count($custTasks),
        'pending_count' => $pending,
        'in_progress_count' => $inProgress,
        'latest_schedule' => $latestSchedule,
        'service_summary' => implode(', ', array_keys($services)),
        'staff_summary' => implode(', ', array_keys($staff)),
    ];
}

usort($customerSummaries, static function (array $a, array $b): int {
    if (($a['task_count'] ?? 0) !== ($b['task_count'] ?? 0)) {
        return ($b['task_count'] ?? 0) <=> ($a['task_count'] ?? 0);
    }
    return strcmp((string)($a['customer_name'] ?? ''), (string)($b['customer_name'] ?? ''));
});

$detailCustomerMonthRows = [];
if ($detailCustomer !== '' && isset($tasksByCustomer[$detailCustomer])) {
    $detailCustomerMonthRows = $tasksByCustomer[$detailCustomer];
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => Constants::APP_ROOT . '/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => Constants::APP_ROOT . '/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => Constants::APP_ROOT . '/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => Constants::APP_ROOT . '/admin/services.php', 'active' => false],
    ['label' => 'Completed Tasks', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php?view=completed', 'active' => false],
    ['label' => 'To Do Tasks', 'href' => Constants::APP_ROOT . '/admin/todo_tasks.php', 'active' => true],
    ['label' => 'Task Assignment', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php', 'active' => false],
    ['label' => 'Reports', 'href' => Constants::APP_ROOT . '/admin/reports.php', 'active' => false],
    ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/admin/complaints.php', 'active' => false],
    ['label' => 'Users', 'href' => Constants::APP_ROOT . '/admin/users.php', 'active' => false],
    ['label' => 'Settings', 'href' => Constants::APP_ROOT . '/admin/settings.php', 'active' => false],
];

ob_start();
?>

<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<?php if ($notice !== ''): ?>
    <div class="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
        <?= e($notice) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">To Do Tasks</h1>
            <p class="mt-1 text-sm text-slate-600">Pending and in-progress tasks summarized customer-wise.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a class="inline-flex items-center justify-center rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/task_assignment.php?view=list&month=<?= e($monthStart->format('Y-m')) ?>">Task Assignment</a>
            <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" href="<?= e(Constants::APP_ROOT) ?>/admin/task_add.php">Assign Task</a>
        </div>
    </div>

    <form class="mt-5 flex flex-col gap-3 lg:flex-row" method="get" action="">
        <input class="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" type="text" name="q" value="<?= e($q) ?>" placeholder="Search by staff, customer, service">
        <input class="rounded-lg border px-3 py-2 text-sm" type="month" name="month" value="<?= e($monthStart->format('Y-m')) ?>">
        <input type="hidden" name="detail_customer" value="<?= e($detailCustomer) ?>">
        <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Apply</button>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/todo_tasks.php">Reset</a>
    </form>

    <div class="mt-6 rounded-2xl border border-slate-200 bg-slate-50 p-4">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <div class="text-sm font-semibold text-slate-900">Customer Summary</div>
                <div class="text-xs text-slate-500">Showing tasks in <?= e($monthStart->format('F Y')) ?>.</div>
            </div>
            <div class="rounded-lg border bg-white px-4 py-2 text-sm font-medium text-slate-700">
                <?= e((string)count($customerSummaries)) ?> customer(s)
            </div>
        </div>

        <div class="mt-4 overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="text-left text-slate-600">
                    <tr class="border-b">
                        <th class="py-2 pr-4">Customer</th>
                        <th class="py-2 pr-4">Staff</th>
                        <th class="py-2 pr-4">Services</th>
                        <th class="py-2 pr-4">Pending</th>
                        <th class="py-2 pr-4">In Progress</th>
                        <th class="py-2 pr-4">Total</th>
                        <th class="py-2 pr-4">Latest Schedule</th>
                        <th class="py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$customerSummaries): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="8">No to do tasks for this month.</td></tr>
                <?php else: ?>
                    <?php foreach ($customerSummaries as $s): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4 font-semibold text-slate-900"><?= e((string)($s['customer_name'] ?? '')) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)($s['staff_summary'] ?? '')) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)(($s['service_summary'] ?? '') !== '' ? $s['service_summary'] : '-')) ?></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-amber-50 px-2 py-1 text-xs font-semibold text-amber-700"><?= e((string)($s['pending_count'] ?? 0)) ?></span></td>
                            <td class="py-3 pr-4"><span class="inline-flex min-w-[2rem] items-center justify-center rounded-full bg-blue-50 px-2 py-1 text-xs font-semibold text-blue-700"><?= e((string)($s['in_progress_count'] ?? 0)) ?></span></td>
                            <td class="py-3 pr-4 font-medium text-slate-900"><?= e((string)($s['task_count'] ?? 0)) ?></td>
                            <td class="py-3 pr-4 text-slate-600"><?= e((string)(($s['latest_schedule'] ?? '') !== '' ? $s['latest_schedule'] : '-')) ?></td>
                            <td class="py-3">
                                <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-slate-800" href="<?= e(Constants::APP_ROOT) ?>/admin/todo_tasks.php?month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>&detail_customer=<?= urlencode((string)($s['customer_name'] ?? '')) ?>#customer-details">Details</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($detailCustomer !== ''): ?>
        <div id="customer-details" class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <div class="text-sm font-semibold text-slate-900">Customer Task Details</div>
                    <div class="text-xs text-slate-500">Showing tasks for <?= e($detailCustomer) ?> in <?= e($monthStart->format('F Y')) ?>.</div>
                </div>
                <div class="flex gap-2">
                    <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/todo_tasks.php?month=<?= e($monthStart->format('Y-m')) ?>&q=<?= urlencode($q) ?>">Close</a>
                </div>
            </div>

            <div class="mt-4 overflow-x-auto">
                <table class="min-w-full text-sm">
                    <thead class="text-left text-slate-600">
                        <tr class="border-b">
                            <th class="py-2 pr-4">Task</th>
                            <th class="py-2 pr-4">Schedule</th>
                            <th class="py-2 pr-4">Staff</th>
                            <th class="py-2 pr-4">Service</th>
                            <th class="py-2 pr-4">Status</th>
                            <th class="py-2">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$detailCustomerMonthRows): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="6">No tasks found for this customer in this month.</td></tr>
                        <?php else: ?>
                            <?php foreach ($detailCustomerMonthRows as $r): ?>
                                <?php $badge = task_status_badge_class((string)($r['task_status'] ?? '')); ?>
                                <tr class="border-b last:border-0">
                                    <td class="py-3 pr-4 font-medium">#<?= e((string)$r['task_id']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['scheduled_date']) ?> <?= e((string)$r['scheduled_time']) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)($r['staff_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)($r['service_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><span class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium <?= e($badge) ?>"><?= e((string)($r['task_status'] ?? '')) ?></span></td>
                                    <td class="py-3">
                                        <div class="flex flex-nowrap gap-2">
                                            <a class="inline-flex items-center justify-center rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700" href="<?= e(Constants::APP_ROOT) ?>/admin/task_details.php?id=<?= e((string)$r['task_id']) ?>">View</a>
                                            <a class="inline-flex items-center justify-center rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-amber-600" href="<?= e(Constants::APP_ROOT) ?>/admin/task_edit.php?id=<?= e((string)$r['task_id']) ?>">Edit</a>
                                            <form method="post" action="<?= e(Constants::APP_ROOT) ?>/admin/task_delete.php" onsubmit="return confirm('Delete this task?');">
                                                <input type="hidden" name="id" value="<?= e((string)$r['task_id']) ?>">
                                                <input type="hidden" name="return_view" value="todo">
                                                <input type="hidden" name="return_month" value="<?= e($monthStart->format('Y-m')) ?>">
                                                <input type="hidden" name="return_detail_staff" value="">
                                                <input type="hidden" name="return_detail_customer" value="<?= e($detailCustomer) ?>">
                                                <button class="inline-flex items-center justify-center rounded-lg bg-red-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-red-700" type="submit">Delete</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
