<?php
require_once __DIR__ . '/../includes/auth.php';
require_customer();
require_once __DIR__ . '/../includes/header_customer.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$userId = current_user()['id'];
$errors = [];

// Fetch fresh user data
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$userId]);
$user = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    if ($name === '') {
        $errors['name'] = 'Nama lengkap wajib diisi.';
    }

    if ($newPassword !== '') {
        if (strlen($newPassword) < 6) {
            $errors['password'] = 'Password minimal 6 karakter.';
        }
        if ($newPassword !== $confirmPassword) {
            $errors['confirm_password'] = 'Konfirmasi password tidak cocok.';
        }
    }

    if (!$errors) {
        try {
            if ($newPassword !== '') {
                // Update with password
                $hash = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare('UPDATE users SET name = ?, phone = ?, address = ?, password_hash = ? WHERE id = ?');
                $stmt->execute([$name, $phone, $address, $hash, $userId]);
                flash_message('success', 'Profil dan password berhasil diperbarui.');
            } else {
                // Update info only
                $stmt = $pdo->prepare('UPDATE users SET name = ?, phone = ?, address = ? WHERE id = ?');
                $stmt->execute([$name, $phone, $address, $userId]);
                flash_message('success', 'Profil berhasil diperbarui.');
            }

            // Refresh Session Data (excluding sensitive info)
            $_SESSION['user']['name'] = $name;
            $_SESSION['user']['phone'] = $phone;
            $_SESSION['user']['address'] = $address;
            
            redirect(base_url('public/index.php?page=profile'));
            
        } catch (PDOException $e) {
            $errors['system'] = 'Gagal menyimpan data: ' . $e->getMessage();
        }
    }
}
?>

<div class="row justify-content-center">
    <div class="col-md-8 col-lg-6">
        <div class="card shadow-sm rounded-4 border-0">
            <div class="card-body p-4">
                <div class="text-center mb-4">
                    <div class="bg-light rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                        <i class="bi bi-person-fill text-secondary" style="font-size: 2.5rem;"></i>
                    </div>
                    <h3 class="fw-bold">Edit Profil</h3>
                    <p class="text-muted small">Perbarui informasi akun Anda di sini.</p>
                </div>

                <?php if (isset($errors['system'])): ?>
                    <div class="alert alert-danger"><?= $errors['system']; ?></div>
                <?php endif; ?>

                <?php if ($msg = flash_message('success')): ?>
                    <div class="alert alert-success"><i class="bi bi-check-circle me-2"></i><?= $msg; ?></div>
                <?php endif; ?>

                <form method="post" autocomplete="off">
                    <h6 class="fw-bold text-uppercase text-muted small mb-3 ls-1">Informasi Pribadi</h6>
                    
                    <div class="mb-3">
                        <label class="form-label text-muted small">Username (Tidak bisa diubah)</label>
                        <input type="text" class="form-control bg-light" value="<?= sanitize($user['username']); ?>" readonly disabled>
                    </div>

                    <div class="mb-3">
                        <label class="form-label text-muted small">Email (Tidak bisa diubah)</label>
                        <input type="email" class="form-control bg-light" value="<?= sanitize($user['email']); ?>" readonly disabled>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Nama Lengkap</label>
                        <input type="text" class="form-control" name="name" value="<?= sanitize($user['name']); ?>" required>
                        <?php if (isset($errors['name'])): ?><small class="text-danger"><?= $errors['name']; ?></small><?php endif; ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Nomor WhatsApp / HP</label>
                        <input type="text" class="form-control" name="phone" value="<?= sanitize($user['phone']); ?>" placeholder="Contoh: 08123456789">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Alamat Pengiriman Default</label>
                        <textarea class="form-control" name="address" rows="3" placeholder="Alamat lengkap untuk pengiriman..."><?= sanitize($user['address']); ?></textarea>
                    </div>

                    <hr class="my-4">

                    <h6 class="fw-bold text-uppercase text-muted small mb-3 ls-1">Keamanan (Opsional)</h6>
                    
                    <div class="mb-3">
                        <label class="form-label">Password Baru <span class="text-muted fw-normal fst-italic">(Kosongkan jika tidak ingin ganti)</span></label>
                        <input type="password" class="form-control" name="new_password" autocomplete="new-password">
                        <?php if (isset($errors['password'])): ?><small class="text-danger"><?= $errors['password']; ?></small><?php endif; ?>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Konfirmasi Password Baru</label>
                        <input type="password" class="form-control" name="confirm_password">
                        <?php if (isset($errors['confirm_password'])): ?><small class="text-danger"><?= $errors['confirm_password']; ?></small><?php endif; ?>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg" style="background: var(--primary-end); border-color: var(--primary-end);">
                            Simpan Perubahan
                        </button>
                        <a href="<?= base_url('public/index.php'); ?>" class="btn btn-outline-secondary">Kembali ke Beranda</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_customer.php'; ?>
