<?php
include __DIR__ . '/includes/header.php';

if (!$user) {
    header('Location: /auth/login.php');
    exit;
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'change_login_password') {
        $old_pwd = $_POST['old_password'] ?? '';
        $new_pwd = $_POST['new_password'] ?? '';
        $confirm_pwd = $_POST['confirm_new_password'] ?? '';
        
        $stmt = db()->prepare("SELECT password_hash FROM users WHERE id = ?");
        $stmt->execute([$user['id']]);
        $current_pwd_hash = $stmt->fetchColumn();
        
        if (!password_verify($old_pwd, $current_pwd_hash)) {
            $error = __("old_pwd_incorrect");
        } elseif ($new_pwd !== $confirm_pwd) {
            $error = __("pwd_mismatch");
        } elseif (strlen($new_pwd) < 6) {
            $error = __("pwd_too_short");
        } else {
            $new_hash = password_hash($new_pwd, PASSWORD_DEFAULT);
            $stmt = db()->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
            $stmt->execute([$new_hash, $user['id']]);
            $success = __("pwd_changed_success");
        }
    } elseif ($action === 'set_trade_password') {
        $trade_pwd = $_POST['trade_password'] ?? '';
        $confirm_trade_pwd = $_POST['confirm_trade_password'] ?? '';
        
        if ($trade_pwd !== $confirm_trade_pwd) {
            $error = __("pwd_mismatch");
        } elseif (strlen($trade_pwd) < 6) {
            $error = __("pwd_too_short");
        } else {
            $trade_hash = password_hash($trade_pwd, PASSWORD_DEFAULT);
            $stmt = db()->prepare("UPDATE users SET transaction_password = ? WHERE id = ?");
            $stmt->execute([$trade_hash, $user['id']]);
            $success = __("trade_pwd_updated");
        }
    }
}

$stmt = db()->prepare("SELECT transaction_password FROM users WHERE id = ?");
$stmt->execute([$user['id']]);
$hasTradePwd = !empty($stmt->fetchColumn());

// Calculate security level
$securityScore = 20; // Base score for having an account
if ($user['email']) $securityScore += 20;
if ($hasTradePwd) $securityScore += 20;
// Placeholders for other security features
$hasPhone = !empty($user['phone'] ?? ''); 
if ($hasPhone) $securityScore += 20;
$hasGoogle = !empty($user['google_2fa_secret'] ?? '');
if ($hasGoogle) $securityScore += 20;

$securityLevelKey = 'low';
$levelClass = 'bg-danger';
if ($securityScore >= 80) {
    $securityLevelKey = 'high';
    $levelClass = 'bg-success';
} elseif ($securityScore >= 50) {
    $securityLevelKey = 'medium';
    $levelClass = 'bg-warning';
}
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="mb-4">
                <a href="/profile.php" class="text-white-50 text-decoration-none d-inline-flex align-items-center gap-2">
                    <i class="bi bi-arrow-left fs-4"></i>
                    <span><?= __('back') ?></span>
                </a>
            </div>

            <div class="card bg-surface border-secondary rounded-4 shadow-lg overflow-hidden mb-4">
                <div class="card-header border-secondary bg-black bg-opacity-30 p-4">
                    <h4 class="mb-0 fw-bold d-flex align-items-center gap-3 text-white">
                        <i class="bi bi-shield-lock-fill text-primary"></i>
                        <?= __('security') ?>
                    </h4>
                </div>
                
                <div class="card-body p-4 p-md-5">
                    <?php if ($success): ?>
                        <div class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 mb-4">
                            <i class="bi bi-check-circle-fill me-2"></i><?= $success ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error): ?>
                        <div class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 mb-4">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $error ?>
                        </div>
                    <?php endif; ?>

                    <!-- Security Level -->
                    <div class="mb-5">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="text-white fw-bold mb-0"><?= __('security_level') ?></h6>
                            <span class="badge <?= $levelClass ?> px-3 py-2 rounded-pill"><?= __($securityLevelKey) ?></span>
                        </div>
                        <div class="progress bg-black bg-opacity-50 rounded-pill shadow-sm" style="height: 10px;">
                            <div class="progress-bar <?= $levelClass ?> progress-bar-striped progress-bar-animated" role="progressbar" style="width: <?= $securityScore ?>%"></div>
                        </div>
                    </div>

                    <!-- Security List -->
                    <div class="security-list">
                        <!-- Phone Binding -->
                        <div class="d-flex align-items-center justify-content-between py-4 border-bottom border-secondary border-opacity-50">
                            <div class="d-flex align-items-center gap-3">
                                <div class="icon-box rounded-circle bg-primary bg-opacity-10 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                    <i class="bi bi-phone text-primary fs-4"></i>
                                </div>
                                <div>
                                    <div class="text-white fw-bold"><?= __('binding_phone') ?></div>
                                    <div class="text-white-50 small"><?= $hasPhone ? htmlspecialchars($user['phone']) : __('not_bound') ?></div>
                                </div>
                            </div>
                            <a href="#" class="btn btn-outline-light btn-sm rounded-pill px-4"><?= __('update') ?></a>
                        </div>

                        <!-- Login Password -->
                        <div class="d-flex align-items-center justify-content-between py-4 border-bottom border-secondary border-opacity-50">
                            <div class="d-flex align-items-center gap-3">
                                <div class="icon-box rounded-circle bg-success bg-opacity-10 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                    <i class="bi bi-key text-success fs-4"></i>
                                </div>
                                <div>
                                    <div class="text-white fw-bold"><?= __('login_password') ?></div>
                                    <div class="text-white-50 small">********</div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-outline-light btn-sm rounded-pill px-4" data-bs-toggle="collapse" data-bs-target="#loginPwdForm"><?= __('update') ?></button>
                        </div>
                        <div class="collapse mt-3" id="loginPwdForm">
                            <div class="p-4 bg-black bg-opacity-20 rounded-4 border border-secondary mb-4">
                                <form method="POST">
                                    <input type="hidden" name="action" value="change_login_password">
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label text-white-50 small fw-bold mb-2"><?= __('old_password') ?></label>
                                            <input type="password" name="old_password" class="form-control bg-dark border-secondary text-white" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label text-white-50 small fw-bold mb-2"><?= __('new_password') ?></label>
                                            <input type="password" name="new_password" class="form-control bg-dark border-secondary text-white" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label text-white-50 small fw-bold mb-2"><?= __('confirm_new_password') ?></label>
                                            <input type="password" name="confirm_new_password" class="form-control bg-dark border-secondary text-white" required>
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary rounded-pill px-4 mt-2"><?= __('confirm') ?></button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Google 2FA -->
                        <div class="d-flex align-items-center justify-content-between py-4 border-bottom border-secondary border-opacity-50">
                            <div class="d-flex align-items-center gap-3">
                                <div class="icon-box rounded-circle bg-warning bg-opacity-10 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                    <i class="bi bi-shield-lock text-warning fs-4"></i>
                                </div>
                                <div>
                                    <div class="text-white fw-bold"><?= __('google_verification') ?></div>
                                    <div class="text-white-50 small"><?= $hasGoogle ? __('bound') : __('not_bound') ?></div>
                                </div>
                            </div>
                            <a href="#" class="btn btn-outline-light btn-sm rounded-pill px-4"><?= __('update') ?></a>
                        </div>

                        <!-- Email Binding -->
                        <div class="d-flex align-items-center justify-content-between py-4">
                            <div class="d-flex align-items-center gap-3">
                                <div class="icon-box rounded-circle bg-info bg-opacity-10 d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                    <i class="bi bi-envelope text-info fs-4"></i>
                                </div>
                                <div>
                                    <div class="text-white fw-bold"><?= __('binding_mailbox') ?></div>
                                    <div class="text-white-50 small"><?= htmlspecialchars($user['email']) ?></div>
                                </div>
                            </div>
                            <a href="#" class="btn btn-outline-light btn-sm rounded-pill px-4"><?= __('update') ?></a>
                        </div>
                    </div>

                    <!-- Trade Password (Existing) -->
                    <div class="mt-5 pt-4 border-top border-secondary border-opacity-50">
                        <div class="d-flex align-items-center justify-content-between mb-4">
                            <h5 class="text-white fw-bold mb-0">
                                <i class="bi bi-safe2 text-warning me-2"></i> <?= __('trade_password') ?>
                            </h5>
                            <button type="button" class="btn btn-warning btn-sm rounded-pill px-4 text-dark fw-bold" data-bs-toggle="collapse" data-bs-target="#tradePwdForm">
                                <?= $hasTradePwd ? __('update') : __('set_password') ?>
                            </button>
                        </div>
                        <div class="collapse" id="tradePwdForm">
                            <div class="p-4 bg-black bg-opacity-20 rounded-4 border border-secondary">
                                <form method="POST">
                                    <input type="hidden" name="action" value="set_trade_password">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label text-white-50 small fw-bold mb-2"><?= $hasTradePwd ? __('new_password') : __('set_password') ?></label>
                                            <input type="password" name="trade_password" class="form-control bg-dark border-secondary text-white" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label text-white-50 small fw-bold mb-2"><?= __('confirm_new_password') ?></label>
                                            <input type="password" name="confirm_trade_password" class="form-control bg-dark border-secondary text-white" required>
                                        </div>
                                        <div class="col-12 text-end">
                                            <button type="submit" class="btn btn-warning rounded-pill px-5 text-dark fw-bold"><?= __('confirm') ?></button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="bg-black bg-opacity-20 rounded-4 p-4 mt-5 border border-secondary border-opacity-50">
                        <h6 class="text-white fw-bold mb-3 d-flex align-items-center gap-2">
                            <i class="bi bi-info-circle text-info"></i> <?= __('security_tips') ?>
                        </h6>
                        <ul class="text-white-50 small mb-0 ps-3">
                            <li class="mb-2"><?= __('security_step1') ?></li>
                            <li><?= __('security_step2') ?></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .icon-box { transition: all 0.3s ease; }
    .security-list > div:hover .icon-box { transform: scale(1.1); }
    .btn-outline-light:hover { background: var(--primary); border-color: var(--primary); }
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>
