<?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();
$title = 'Edit Staff';

$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' => true],
    ['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' => false],
    ['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 = '';

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare(
        "SELECT u.user_id, u.full_name, u.email, u.phone, u.address, u.is_active,
                sd.employee_code, sd.position, sd.specialization, sd.hire_date, sd.hourly_rate, sd.is_available
         FROM users u
         LEFT JOIN staff_details sd ON sd.user_id = u.user_id
         WHERE u.user_id = :id AND u.user_type = 'staff'
         LIMIT 1"
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo 'Staff not found';
        exit;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
    $row = null;
}

$values = [
    'full_name' => (string)($row['full_name'] ?? ''),
    'email' => (string)($row['email'] ?? ''),
    'password' => '',
    'phone' => (string)($row['phone'] ?? ''),
    'address' => (string)($row['address'] ?? ''),
    'employee_code' => (string)($row['employee_code'] ?? ''),
    'position' => (string)($row['position'] ?? ''),
    'specialization' => (string)($row['specialization'] ?? ''),
    'hire_date' => (string)($row['hire_date'] ?? ''),
    'hourly_rate' => (string)($row['hourly_rate'] ?? ''),
    'is_active' => ((int)($row['is_active'] ?? 1) === 1) ? '1' : '0',
    'is_available' => ((int)($row['is_available'] ?? 1) === 1) ? '1' : '0',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($values as $k => $v) {
        $values[$k] = trim((string)($_POST[$k] ?? ''));
    }

    if ($values['full_name'] === '' || $values['email'] === '' || $values['employee_code'] === '') {
        $error = 'Full name, email, and employee code are required.';
    } elseif (!filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address.';
    } else {
        try {
            $pdo = Database::pdo();
            $pdo->beginTransaction();

            if ($values['password'] !== '') {
                $hash = password_hash($values['password'], PASSWORD_BCRYPT);
                $stmtU = $pdo->prepare(
                    'UPDATE users SET email=:email, full_name=:full_name, phone=:phone, address=:address, is_active=:is_active, password_hash=:password_hash WHERE user_id=:id AND user_type=\'staff\''
                );
                $stmtU->execute([
                    'email' => $values['email'],
                    'full_name' => $values['full_name'],
                    'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                    'address' => ($values['address'] !== '' ? $values['address'] : null),
                    'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                    'password_hash' => $hash,
                    'id' => $id,
                ]);
            } else {
                $stmtU = $pdo->prepare(
                    'UPDATE users SET email=:email, full_name=:full_name, phone=:phone, address=:address, is_active=:is_active WHERE user_id=:id AND user_type=\'staff\''
                );
                $stmtU->execute([
                    'email' => $values['email'],
                    'full_name' => $values['full_name'],
                    'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                    'address' => ($values['address'] !== '' ? $values['address'] : null),
                    'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                    'id' => $id,
                ]);
            }

            $stmtS = $pdo->prepare(
                'UPDATE staff_details SET employee_code=:employee_code, position=:position, specialization=:specialization, hire_date=:hire_date, hourly_rate=:hourly_rate, is_available=:is_available WHERE user_id=:id'
            );
            $stmtS->execute([
                'employee_code' => $values['employee_code'],
                'position' => ($values['position'] !== '' ? $values['position'] : null),
                'specialization' => ($values['specialization'] !== '' ? $values['specialization'] : null),
                'hire_date' => ($values['hire_date'] !== '' ? $values['hire_date'] : null),
                'hourly_rate' => ($values['hourly_rate'] !== '' ? (float)$values['hourly_rate'] : null),
                'is_available' => ((int)$values['is_available'] === 1) ? 1 : 0,
                'id' => $id,
            ]);

            $pdo->commit();

            header('Location: /pest/public/admin/staff.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 Staff</h1>
            <p class="mt-1 text-sm text-slate-600">Update staff user details.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/staff.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="">
        <div>
            <label class="block text-sm font-medium">Full name</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="full_name" value="<?= e($values['full_name']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">Email</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="email" name="email" value="<?= e($values['email']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">New password (optional)</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="text" name="password" value="">
        </div>
        <div>
            <label class="block text-sm font-medium">Phone</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="phone" value="<?= e($values['phone']) ?>">
        </div>
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Address</label>
            <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="address" rows="2"><?= e($values['address']) ?></textarea>
        </div>

        <div>
            <label class="block text-sm font-medium">Employee code</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="employee_code" value="<?= e($values['employee_code']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">Position</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="position" value="<?= e($values['position']) ?>">
        </div>
        <div>
            <label class="block text-sm font-medium">Specialization</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="specialization" value="<?= e($values['specialization']) ?>">
        </div>
        <div>
            <label class="block text-sm font-medium">Hire date</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="date" name="hire_date" value="<?= e($values['hire_date']) ?>">
        </div>
        <div>
            <label class="block text-sm font-medium">Hourly rate</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="number" step="0.01" name="hourly_rate" value="<?= e($values['hourly_rate']) ?>">
        </div>

        <div>
            <label class="block text-sm font-medium">Active</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="is_active">
                <option value="1" <?= ($values['is_active'] === '1') ? 'selected' : '' ?>>Yes</option>
                <option value="0" <?= ($values['is_active'] === '0') ? 'selected' : '' ?>>No</option>
            </select>
        </div>
        <div>
            <label class="block text-sm font-medium">Available</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="is_available">
                <option value="1" <?= ($values['is_available'] === '1') ? 'selected' : '' ?>>Yes</option>
                <option value="0" <?= ($values['is_available'] === '0') ? 'selected' : '' ?>>No</option>
            </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>
<?php
$content = ob_get_clean();

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