<?php

declare(strict_types=1);

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

$config = require __DIR__ . '/../../config/config.php';

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

$user = auth_user();
$title = 'Task History';

$staffId = (int)($user['user_id'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));
$rows = [];
$error = '';
$notice = trim((string)($_GET['notice'] ?? ''));

function table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int)$stmt->fetchColumn() > 0;
}

function ensure_staff_task_hides_table(PDO $pdo): void
{
    if (table_exists($pdo, 'staff_task_hides')) {
        return;
    }
    $pdo->exec(
        'CREATE TABLE IF NOT EXISTS staff_task_hides (
            staff_id INT NOT NULL,
            task_id INT NOT NULL,
            hidden_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (staff_id, task_id),
            KEY idx_task_id (task_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'
    );
}

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

    ensure_staff_task_hides_table($pdo);

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hide_task_id'])) {
        $hideTaskId = (int)($_POST['hide_task_id'] ?? 0);
        if ($hideTaskId <= 0) {
            throw new RuntimeException('Invalid task selection.');
        }

        $stmtOwn = $pdo->prepare('SELECT task_id FROM tasks WHERE task_id = :tid AND assigned_staff_id = :sid LIMIT 1');
        $stmtOwn->execute(['tid' => $hideTaskId, 'sid' => $staffId]);
        $own = (int)($stmtOwn->fetchColumn() ?: 0);
        if ($own <= 0) {
            throw new RuntimeException('Invalid task selection.');
        }

        $stmtHide = $pdo->prepare('INSERT IGNORE INTO staff_task_hides (staff_id, task_id) VALUES (:sid, :tid)');
        $stmtHide->execute(['sid' => $staffId, 'tid' => $hideTaskId]);

        $redir = '/pest/public/staff/history.php';
        if ($q !== '') {
            $redir .= '?q=' . urlencode($q) . '&notice=' . urlencode('Removed from history.');
        } else {
            $redir .= '?notice=' . urlencode('Removed from history.');
        }
        header('Location: ' . $redir);
        exit;
    }

    if ($q !== '') {
        $stmt = $pdo->prepare(
            "SELECT a.task_id, a.scheduled_date, a.scheduled_time, a.task_status, a.customer_name, a.service_name
             FROM admin_all_tasks a
             JOIN tasks t ON t.task_id = a.task_id
             LEFT JOIN staff_task_hides h ON h.staff_id = :sid_join AND h.task_id = a.task_id
             WHERE t.assigned_staff_id = :sid_where
               AND a.task_status IN ('completed','cancelled')
               AND h.task_id IS NULL
               AND (a.customer_name LIKE :q OR a.service_name LIKE :q OR a.task_status LIKE :q)
             ORDER BY a.scheduled_date DESC, a.scheduled_time DESC"
        );
        $stmt->execute([
            'sid_join' => $staffId,
            'sid_where' => $staffId,
            'q' => '%' . $q . '%',
        ]);
        $rows = $stmt->fetchAll();
    } else {
        $stmt = $pdo->prepare(
            "SELECT a.task_id, a.scheduled_date, a.scheduled_time, a.task_status, a.customer_name, a.service_name
             FROM admin_all_tasks a
             JOIN tasks t ON t.task_id = a.task_id
             LEFT JOIN staff_task_hides h ON h.staff_id = :sid_join AND h.task_id = a.task_id
             WHERE t.assigned_staff_id = :sid_where
               AND a.task_status IN ('completed','cancelled')
               AND h.task_id IS NULL
             ORDER BY a.scheduled_date DESC, a.scheduled_time DESC"
        );
        $stmt->execute(['sid_join' => $staffId, 'sid_where' => $staffId]);
        $rows = $stmt->fetchAll();
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/staff/overview.php', 'active' => false],
    ['label' => 'My Tasks', 'href' => '/pest/public/staff/index.php', 'active' => false],
    ['label' => 'Upload Images', 'href' => '/pest/public/staff/upload_images.php', 'active' => false],
    ['label' => 'Location Tracker', 'href' => '/pest/public/staff/location.php', 'active' => false],
    ['label' => 'Task History', 'href' => '/pest/public/staff/history.php', 'active' => true],
];

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 !== '' && $error === ''): ?>
    <div class="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-700">
        <?= e($notice) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Task History</h1>
            <p class="mt-1 text-sm text-slate-600">Completed and cancelled tasks assigned to you.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/index.php">Back</a>
    </div>

    <form class="mt-5 flex gap-2" 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 customer, service, status">
        <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Search</button>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/history.php">Reset</a>
    </form>

    <div class="mt-5 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 ID</th>
                    <th class="py-2 pr-4">Customer</th>
                    <th class="py-2 pr-4">Service</th>
                    <th class="py-2 pr-4">Date</th>
                    <th class="py-2 pr-4">Time</th>
                    <th class="py-2 pr-4">Status</th>
                    <th class="py-2">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$rows): ?>
                    <tr class="border-b"><td class="py-3 text-slate-500" colspan="7">No history found.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $t): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4 font-medium"><?= e((string)$t['task_id']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($t['customer_name'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($t['service_name'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($t['scheduled_date'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($t['scheduled_time'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($t['task_status'] ?? '')) ?></td>
                            <td class="py-3">
                                <div class="flex flex-wrap gap-2">
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/staff/task_details.php?id=<?= e((string)$t['task_id']) ?>">View</a>
                                    <form method="post" action="" onsubmit="return confirm('Remove this task from your history list?');">
                                        <input type="hidden" name="hide_task_id" value="<?= e((string)$t['task_id']) ?>">
                                        <button class="rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-xs text-rose-700 hover:bg-rose-100" type="submit">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
