<?php
$pageTitle = 'My Profile';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();
$currentUser = $db->query("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']])->fetch();
?>

<div class="row">
    <div class="col-md-6">
        <div class="form-card">
            <h6 class="text-primary mb-3"><i class="fas fa-user me-2"></i>Edit Profile</h6>
            <form id="profileForm" action="profile_save.php" method="POST">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" value="update_profile">
                <div class="mb-3">
                    <label class="form-label">Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="name" value="<?php echo sanitize($currentUser['name']); ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email <span class="text-danger">*</span></label>
                    <input type="email" class="form-control" name="email" value="<?php echo sanitize($currentUser['email']); ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Phone</label>
                    <input type="text" class="form-control" name="phone" value="<?php echo sanitize($currentUser['phone'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label class="form-label">Avatar</label>
                    <input type="file" class="form-control" name="avatar" accept="image/*" data-preview="#avatarPreview">
                    <?php if (!empty($currentUser['avatar'])): ?>
                        <img id="avatarPreview" class="img-preview mt-2" src="<?php echo getBaseUrl() . '/' . $currentUser['avatar']; ?>">
                    <?php else: ?>
                        <div class="avatar-circle mt-2" style="width:80px;height:80px;font-size:32px;"><?php echo strtoupper(substr($currentUser['name'], 0, 1)); ?></div>
                    <?php endif; ?>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Update Profile</button>
            </form>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-card" id="change-password">
            <h6 class="text-primary mb-3"><i class="fas fa-lock me-2"></i>Change Password</h6>
            <form id="passwordForm" action="profile_save.php" method="POST">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" value="change_password">
                <div class="mb-3">
                    <label class="form-label">Current Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control" name="current_password" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">New Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control" name="new_password" required minlength="6">
                </div>
                <div class="mb-3">
                    <label class="form-label">Confirm New Password <span class="text-danger">*</span></label>
                    <input type="password" class="form-control" name="confirm_password" required minlength="6">
                </div>
                <button type="submit" class="btn btn-warning"><i class="fas fa-key me-1"></i>Change Password</button>
            </form>
        </div>

        <div class="form-card">
            <h6 class="text-primary mb-3"><i class="fas fa-info-circle me-2"></i>Account Info</h6>
            <div class="mb-2"><strong>Role:</strong> <?php echo ucfirst(str_replace('_', ' ', $currentUser['role_id'] == 1 ? 'Super Admin' : 'User')); ?></div>
            <div class="mb-2"><strong>Email:</strong> <?php echo sanitize($currentUser['email']); ?></div>
            <div class="mb-2"><strong>Last Login:</strong> <?php echo $currentUser['last_login'] ? formatDateTime($currentUser['last_login']) : 'Never'; ?></div>
            <div class="mb-2"><strong>Member Since:</strong> <?php echo formatDate($currentUser['created_at']); ?></div>
        </div>
    </div>
</div>

<script>
document.getElementById('profileForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var fd = new FormData(this);
    fetch(BASE_URL + '/admin/profile_save.php', { method: 'POST', body: fd, processData: false, contentType: false })
    .then(function(r) { return r.json(); })
    .then(function(d) { if (d.success) { showAlert('success', d.message); } else { showAlert('danger', d.message); } });
});

document.getElementById('passwordForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var newPwd = document.querySelector('#passwordForm input[name="new_password"]').value;
    var confirmPwd = document.querySelector('#passwordForm input[name="confirm_password"]').value;
    if (newPwd !== confirmPwd) { showAlert('danger', 'Passwords do not match.'); return; }
    var fd = new FormData(this);
    fetch(BASE_URL + '/admin/profile_save.php', { method: 'POST', body: new URLSearchParams(fd) })
    .then(function(r) { return r.json(); })
    .then(function(d) { if (d.success) { showAlert('success', d.message); document.getElementById('passwordForm').reset(); } else { showAlert('danger', d.message); } });
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
