<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';

$msg = '';
$error = '';
$account = admin_client_account();

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $old = (string)($_POST['old_password'] ?? '');
    $new = (string)($_POST['new_password'] ?? '');
    $new2 = (string)($_POST['new_password_confirm'] ?? '');

    if($old === ''){
        $error = '请输入原密码';
    }elseif(!admin_password_ok($old)){
        $error = '原密码不正确';
    }elseif(strlen($new) < 6){
        $error = '新密码至少需要 6 位';
    }elseif($new !== $new2){
        $error = '两次输入的新密码不一致';
    }else{
        $hash = password_hash($new, PASSWORD_DEFAULT);
        $account['password_hash'] = $hash;
        $account['password_set_at'] = date('Y-m-d H:i:s');
        $account['account'] = $account['account'] ?? admin_login_user();
        $account['domain'] = license_current_domain();

        list($ok, $reqMsg, $json) = admin_register_center_sync($account);
        $account['sync_status'] = $ok && !empty($json['ok']) ? 'success' : 'failed';
        $account['sync_message'] = $ok ? ($json['message'] ?? $reqMsg) : $reqMsg;
        $account['customer_id'] = $json['customer_id'] ?? ($account['customer_id'] ?? '');
        $account['last_sync_at'] = date('Y-m-d H:i:s');
        admin_client_account_save($account);
        admin_oplog('change_password', admin_login_user() . ' / ' . $account['sync_status']);
        $msg = $account['sync_status'] === 'success' ? '密码已修改，并已同步到授权中心' : '密码已修改，但同步授权中心失败：' . $account['sync_message'];
    }
}

admin_header('修改密码');
?>
<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>
<?php if($error): ?><div class="error"><?php echo admin_h($error); ?></div><?php endif; ?>
<div class="card">
    <div class="password-layout">
        <section class="password-form-panel">
            <h2>修改后台登录密码</h2>
            <form method="post" class="password-form">
                <label>原密码<input name="old_password" type="password" autocomplete="current-password" placeholder="请输入当前登录密码"></label>
                <div class="form-grid two">
                    <label>新密码<input name="new_password" type="password" autocomplete="new-password" placeholder="至少 6 位"></label>
                    <label>确认新密码<input name="new_password_confirm" type="password" autocomplete="new-password" placeholder="请再次输入新密码"></label>
                </div>
                <p class="form-actions-left"><button>保存并同步授权中心</button></p>
            </form>
            <div class="warn password-warn">安全说明：系统只同步加密后的 password_hash，不会向授权中心提交明文密码。</div>
        </section>
    </div>
</div>
<?php admin_footer(); ?>
