<?php
$pageTitle = 'Edit Pelanggan';
$activeMenu = 'clients';
require_once __DIR__ . '/../../includes/header.php';

$db = get_db_connection();
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id <= 0) {
    redirect_with_message('index.php', 'Data pelanggan tidak ditemukan.', 'danger');
}

$stmt = $db->prepare('SELECT * FROM clients WHERE id = ? LIMIT 1');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$client = $result->fetch_assoc();

if (!$client) {
    redirect_with_message('index.php', 'Data pelanggan tidak ditemukan.', 'danger');
}

$errors = [];
$formData = [
    'client_code' => $client['client_code'],
    'full_name' => $client['full_name'],
    'phone' => $client['phone'],
    'address' => $client['address'],
    'status' => $client['status'],
    'registration_date' => $client['registration_date'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!validate_csrf_token($token)) {
        $errors[] = 'Token tidak sah. Silakan coba lagi.';
    }

    $formData['client_code'] = sanitize_input($_POST['client_code'] ?? '');
    $formData['full_name'] = sanitize_input($_POST['full_name'] ?? '');
    $formData['phone'] = sanitize_input($_POST['phone'] ?? '');
    $formData['address'] = sanitize_input($_POST['address'] ?? '');
    $formData['status'] = sanitize_input($_POST['status'] ?? 'active');
    $formData['registration_date'] = $_POST['registration_date'] ?? $client['registration_date'];

    if ($formData['client_code'] === '') {
        $errors[] = 'Kode pelanggan wajib diisi.';
    }
    if ($formData['full_name'] === '') {
        $errors[] = 'Nama lengkap wajib diisi.';
    }
    if ($formData['phone'] === '') {
        $errors[] = 'Nomor telepon wajib diisi.';
    }
    if ($formData['registration_date'] === '') {
        $errors[] = 'Tanggal registrasi wajib diisi.';
    }
    if (!in_array($formData['status'], ['active', 'suspended', 'terminated'], true)) {
        $errors[] = 'Status tidak valid.';
    }

    $stmtCheck = $db->prepare('SELECT id FROM clients WHERE client_code = ? AND id <> ? LIMIT 1');
    if ($stmtCheck) {
        $stmtCheck->bind_param('si', $formData['client_code'], $id);
        $stmtCheck->execute();
        $stmtCheck->store_result();
        if ($stmtCheck->num_rows > 0) {
            $errors[] = 'Kode pelanggan sudah digunakan oleh data lain.';
        }
    }

    if (empty($errors)) {
        $sql = 'UPDATE clients SET client_code = ?, full_name = ?, phone = ?, address = ?, status = ?, registration_date = ? WHERE id = ?';
        $stmtUpdate = $db->prepare($sql);
        if ($stmtUpdate) {
            $stmtUpdate->bind_param(
                'ssssssi',
                $formData['client_code'],
                $formData['full_name'],
                $formData['phone'],
                $formData['address'],
                $formData['status'],
                $formData['registration_date'],
                $id
            );

            if ($stmtUpdate->execute()) {
                redirect_with_message('index.php', 'Data pelanggan berhasil diperbarui.');
            }

            $errors[] = 'Gagal memperbarui data pelanggan.';
        } else {
            $errors[] = 'Terjadi kesalahan pada database.';
        }
    }
}

$token = csrf_token();
?>
<div class="card card-metric p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <small class="text-muted">Perbarui informasi pelanggan berikut.</small>
        </div>
        <a href="index.php" class="btn btn-outline-secondary"><i class="fa-solid fa-arrow-left me-2"></i>Kembali</a>
    </div>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    <form method="POST" class="row gy-3 needs-validation" novalidate>
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
        <div class="col-md-6">
            <label class="form-label">Kode Pelanggan</label>
            <input type="text" name="client_code" class="form-control" value="<?php echo htmlspecialchars($formData['client_code']); ?>" required>
            <div class="invalid-feedback">Kode pelanggan wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Tanggal Registrasi</label>
            <input type="date" name="registration_date" class="form-control" value="<?php echo htmlspecialchars($formData['registration_date']); ?>" required>
            <div class="invalid-feedback">Tanggal registrasi wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Nama Lengkap</label>
            <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($formData['full_name']); ?>" required>
            <div class="invalid-feedback">Nama pelanggan wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Nomor Telepon</label>
            <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($formData['phone']); ?>" required>
            <div class="invalid-feedback">Nomor telepon wajib diisi.</div>
        </div>
        <div class="col-12">
            <label class="form-label">Alamat</label>
            <textarea name="address" rows="3" class="form-control" required><?php echo htmlspecialchars($formData['address']); ?></textarea>
            <div class="invalid-feedback">Alamat wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Status</label>
            <select name="status" class="form-select" required>
                <option value="active" <?php echo $formData['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="suspended" <?php echo $formData['status'] === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                <option value="terminated" <?php echo $formData['status'] === 'terminated' ? 'selected' : ''; ?>>Terminated</option>
            </select>
            <div class="invalid-feedback">Pilih status pelanggan.</div>
        </div>
        <div class="col-12">
            <button type="submit" class="btn btn-primary">Perbarui</button>
        </div>
    </form>
</div>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
