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

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

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare(
        "SELECT user_id, full_name, email, phone, address, is_active
         FROM users
         WHERE user_id = :id AND user_type = 'customer'
         LIMIT 1"
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['full_name'] = trim((string)($_POST['full_name'] ?? ''));
    $values['email'] = trim((string)($_POST['email'] ?? ''));
    $values['password'] = trim((string)($_POST['password'] ?? ''));
    $values['phone'] = trim((string)($_POST['phone'] ?? ''));
    $values['address'] = trim((string)($_POST['address'] ?? ''));
    $values['is_active'] = trim((string)($_POST['is_active'] ?? '1'));

    if ($values['full_name'] === '' || $values['email'] === '') {
        $error = 'Name and email are required.';
    } elseif (!filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address.';
    } else {
        try {
            $pdo = Database::pdo();

            $stmtCheck = $pdo->prepare('SELECT COUNT(*) FROM users WHERE email = :email AND user_id <> :id');
            $stmtCheck->execute(['email' => $values['email'], 'id' => $id]);
            if ((int)$stmtCheck->fetchColumn() > 0) {
                $error = 'Email already exists.';
            } else {
                if ($values['password'] !== '') {
                    $hash = password_hash($values['password'], PASSWORD_BCRYPT);
                    $stmtU = $pdo->prepare(
                        "UPDATE users
                         SET full_name=:full_name, email=:email, password_hash=:password_hash, phone=:phone, address=:address, is_active=:is_active
                         WHERE user_id=:id AND user_type='customer'"
                    );
                    $stmtU->execute([
                        'full_name' => $values['full_name'],
                        'email' => $values['email'],
                        'password_hash' => $hash,
                        'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                        'address' => ($values['address'] !== '' ? $values['address'] : null),
                        'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                        'id' => $id,
                    ]);
                } else {
                    $stmtU = $pdo->prepare(
                        "UPDATE users
                         SET full_name=:full_name, email=:email, phone=:phone, address=:address, is_active=:is_active
                         WHERE user_id=:id AND user_type='customer'"
                    );
                    $stmtU->execute([
                        'full_name' => $values['full_name'],
                        'email' => $values['email'],
                        'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                        'address' => ($values['address'] !== '' ? $values['address'] : null),
                        'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                        'id' => $id,
                    ]);
                }

                header('Location: /pest/public/admin/customers.php');
                exit;
            }
        } catch (Throwable $e) {
            $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 Customer</h1>
            <p class="mt-1 text-sm text-slate-600">Update customer details. Leave password blank to keep unchanged.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/customers.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">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</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="password" 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>
            <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 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="3"><?= e($values['address']) ?></textarea>
        </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';
