<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$adminId = (int)($user['user_id'] ?? 0);
$title = 'Edit Task';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo 'Invalid ID';
    exit;
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => true],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
];

$error = '';
$row = null;
$staffList = [];
$checklist = null;
$boxNos = [];
$boxTypeCounts = ['glue_box_count' => 0, 'bait_box_count' => 0, 'efk_count' => 0];

$checkFields = [
    'fumigation_completed' => 'Fumigation Completed',
    'bait_box_checked' => 'Bait Box Checked',
    'glue_box_checked' => 'Glue Box Checked',
    'efk_checked' => "E.F.K's Checked",
    'ilt_checked' => "I.L.T 's Checked",
    'others_checked' => "Other's",
];

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

    $stmt = $pdo->prepare(
        "SELECT t.task_id, t.request_id, t.assigned_staff_id, t.scheduled_date, t.scheduled_time, t.status
         FROM tasks t
         WHERE t.task_id = :id
         LIMIT 1"
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo 'Task not found';
        exit;
    }

    $checklist = TaskChecklistService::get($pdo, $id);
    $boxNos = TaskBoxService::getBoxNos($pdo, $id);
    $boxTypeCounts = TaskBoxTypeService::getCounts($pdo, $id);

    $staffList = $pdo->query(
        "SELECT u.user_id, u.full_name, sd.employee_code
         FROM users u
         JOIN staff_details sd ON sd.user_id = u.user_id
         WHERE u.user_type = 'staff' AND u.is_active = 1
         ORDER BY u.full_name ASC"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$values = [
    'assigned_staff_id' => (string)($row['assigned_staff_id'] ?? ''),
    'scheduled_date' => (string)($row['scheduled_date'] ?? ''),
    'scheduled_time' => (string)($row['scheduled_time'] ?? ''),
    'status' => (string)($row['status'] ?? ''),
];

$allowedStatuses = ['assigned', 'accepted', 'started', 'completed', 'cancelled', 'rescheduled'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['assigned_staff_id'] = trim((string)($_POST['assigned_staff_id'] ?? ''));
    $values['scheduled_date'] = trim((string)($_POST['scheduled_date'] ?? ''));
    $values['scheduled_time'] = trim((string)($_POST['scheduled_time'] ?? ''));
    $values['status'] = trim((string)($_POST['status'] ?? ''));
    $boxInput = (string)($_POST['box_nos'] ?? '');
    $glueCount = (int)($_POST['glue_box_count'] ?? 0);
    $baitCount = (int)($_POST['bait_box_count'] ?? 0);
    $efkCount = (int)($_POST['efk_count'] ?? 0);

    $newStaffId = (int)$values['assigned_staff_id'];
    $oldStaffId = (int)($row['assigned_staff_id'] ?? 0);

    if ($newStaffId <= 0 || $values['scheduled_date'] === '' || $values['scheduled_time'] === '' || !in_array($values['status'], $allowedStatuses, true)) {
        $error = 'All fields are required.';
    } else {
        try {
            $pdo = Database::pdo();
            $pdo->beginTransaction();

            $stmtU = $pdo->prepare(
                'UPDATE tasks SET assigned_staff_id=:staff_id, scheduled_date=:scheduled_date, scheduled_time=:scheduled_time, status=:status, updated_at=CURRENT_TIMESTAMP WHERE task_id=:id'
            );
            $stmtU->execute([
                'staff_id' => $newStaffId,
                'scheduled_date' => $values['scheduled_date'],
                'scheduled_time' => $values['scheduled_time'],
                'status' => $values['status'],
                'id' => $id,
            ]);

            $flags = [];
            foreach ($checkFields as $k => $label) {
                $flags[$k] = !empty($_POST[$k]);
            }
            $flags['others_text'] = (string)($_POST['others_text'] ?? '');
            TaskChecklistService::save($pdo, $id, $flags, $adminId);

            $parsedBoxes = TaskBoxService::parseBoxNos($boxInput);
            TaskBoxService::setBoxNos($pdo, $id, $parsedBoxes, $adminId);

            TaskBoxTypeService::setCounts($pdo, $id, $glueCount, $baitCount, $efkCount, $adminId);

            if ($newStaffId !== $oldStaffId) {
                if ($oldStaffId > 0) {
                    $pdo->prepare('UPDATE staff_details SET is_available = 1 WHERE user_id = :uid')->execute(['uid' => $oldStaffId]);
                }
                $pdo->prepare('UPDATE staff_details SET is_available = 0 WHERE user_id = :uid')->execute(['uid' => $newStaffId]);
            }

            $pdo->commit();

            header('Location: /pest/public/admin/task_assignment.php');
            exit;
        } catch (Throwable $e) {
            if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = $e->getMessage();
        }
    }
}

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; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-xl font-semibold">Edit Task</h1>
            <p class="mt-1 text-sm text-slate-600">Update assigned staff, schedule, and status.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/task_assignment.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="">
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Assigned staff</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="assigned_staff_id" required>
                <option value="">Select staff</option>
                <?php foreach ($staffList as $s): ?>
                    <option value="<?= e((string)$s['user_id']) ?>" <?= ($values['assigned_staff_id'] === (string)$s['user_id']) ? 'selected' : '' ?>>
                        <?= e((string)$s['full_name']) ?> (<?= e((string)$s['employee_code']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="md:col-span-2">
            <div class="text-sm font-semibold">Additional Checklist</div>
            <div class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2">
                <?php foreach ($checkFields as $k => $label): ?>
                    <?php $isChecked = !empty($checklist[$k]); ?>
                    <label class="flex items-center gap-2 rounded-lg border bg-white px-3 py-2 text-sm">
                        <input class="chk" type="checkbox" name="<?= e($k) ?>" value="1" <?= $isChecked ? 'checked' : '' ?> <?= ($k === 'others_checked') ? 'data-others="1"' : '' ?>>
                        <span><?= e($label) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>

            <div id="othersTextWrap" class="mt-3" style="display: <?= !empty($checklist['others_checked']) ? 'block' : 'none' ?>">
                <label class="block text-sm font-medium">Other's (details)</label>
                <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="text" name="others_text" value="<?= e((string)($checklist['others_text'] ?? '')) ?>" placeholder="Enter details...">
            </div>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Box No(s)</label>
            <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="box_nos" rows="3" placeholder="Example: 1,2,3 or B1\nB2\nB3"><?php
                $boxValue = '';
                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                    $boxValue = (string)($_POST['box_nos'] ?? '');
                } else {
                    $boxValue = implode("\n", $boxNos);
                }
                echo e($boxValue);
            ?></textarea>
            <div class="mt-1 text-xs text-slate-500">Enter box numbers separated by commas or new lines.</div>
        </div>

        <div class="md:col-span-2">
            <div class="text-sm font-semibold">Box Types</div>
            <div class="mt-3 grid grid-cols-1 gap-4 md:grid-cols-3">
                <div>
                    <label class="block text-sm font-medium">Glue Box</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" name="glue_box_count" min="0" value="<?= e((string)($_SERVER['REQUEST_METHOD'] === 'POST' ? (string)($_POST['glue_box_count'] ?? '0') : (string)($boxTypeCounts['glue_box_count'] ?? 0))) ?>">
                </div>
                <div>
                    <label class="block text-sm font-medium">Bait Box</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" name="bait_box_count" min="0" value="<?= e((string)($_SERVER['REQUEST_METHOD'] === 'POST' ? (string)($_POST['bait_box_count'] ?? '0') : (string)($boxTypeCounts['bait_box_count'] ?? 0))) ?>">
                </div>
                <div>
                    <label class="block text-sm font-medium">E.F.K - Electric Fly Killer</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" name="efk_count" min="0" value="<?= e((string)($_SERVER['REQUEST_METHOD'] === 'POST' ? (string)($_POST['efk_count'] ?? '0') : (string)($boxTypeCounts['efk_count'] ?? 0))) ?>">
                </div>
            </div>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Scheduled date</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="date" name="scheduled_date" value="<?= e($values['scheduled_date']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">Scheduled time</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="time" name="scheduled_time" value="<?= e($values['scheduled_time']) ?>" required>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Status</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="status" required>
                <?php foreach ($allowedStatuses as $st): ?>
                    <option value="<?= e($st) ?>" <?= ($values['status'] === $st) ? 'selected' : '' ?>><?= e($st) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="md:col-span-2">
            <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Save changes</button>
        </div>
    </form>
</div>
<script>
    (function () {
        var wrap = document.getElementById('othersTextWrap');
        var cb = document.querySelector('input[data-others="1"]');
        function sync() {
            if (!wrap || !cb) return;
            wrap.style.display = cb.checked ? '' : 'none';
        }
        cb && cb.addEventListener('change', sync);
        sync();
    })();
</script>
<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
