<?php
require_once 'includes/header.php';

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

$msg = '';
$error = '';

// Initialize default security password if empty
if (empty($user['security_password'])) {
    $default_sec = password_hash('123456', PASSWORD_DEFAULT);
    try {
        db()->prepare("UPDATE users SET security_password = ? WHERE id = ?")->execute([$default_sec, $user['id']]);
        $user['security_password'] = $default_sec;
    } catch (Exception $e) {}
}

// Handle KYC upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['kyc_submit'])) {
    $real_name = $_POST['real_name'] ?? '';
    $id_number = $_POST['id_number'] ?? '';
    
    try {
        $stmt = db()->prepare("UPDATE users SET real_name = ?, id_number = ?, kyc_status = 'pending' WHERE id = ?");
        $stmt->execute([$real_name, $id_number, $user['id']]);
        $msg = mt('Identity verification submitted and is under review.');
        $user['kyc_status'] = 'pending';
    } catch (Exception $e) {
        $error = mt('Error') . ': ' . $e->getMessage();
    }
}

// Handle Password Changes
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $type = $_POST['type'] ?? 'login'; // 'login' or 'security'
    $old_pass = $_POST['old_password'] ?? '';
    $new_pass = $_POST['new_password'] ?? '';
    $confirm_pass = $_POST['confirm_password'] ?? '';
    
    if ($new_pass !== $confirm_pass) {
        $error = mt('New passwords do not match.');
    } elseif (strlen($new_pass) < 6) {
        $error = mt('Password must be at least 6 characters.');
    } else {
        $current_hash = ($type === 'login') ? $user['password_hash'] : $user['security_password'];
        if (password_verify($old_pass, $current_hash)) {
            $new_hash = password_hash($new_pass, PASSWORD_DEFAULT);
            $column = ($type === 'login') ? 'password_hash' : 'security_password';
            try {
                db()->prepare("UPDATE users SET $column = ? WHERE id = ?")->execute([$new_hash, $user['id']]);
                $msg = mt('Password updated successfully.');
            } catch (Exception $e) {
                $error = mt('Update failed') . ': ' . $e->getMessage();
            }
        } else {
            $error = mt('Current password incorrect.');
        }
    }
}
?>

<style>
    .profile-container {
        padding: 40px 0;
        min-height: 80vh;
    }
    .side-nav {
        background-color: #181a20;
        border-radius: 24px;
        padding: 20px;
        border: 1px solid #2b2f36;
    }
    .side-nav .nav-link {
        color: #848e9c;
        padding: 15px 20px;
        border-radius: 12px;
        margin-bottom: 5px;
        font-weight: 500;
        transition: all 0.3s;
        border: none;
        width: 100%;
        text-align: left;
    }
    .side-nav .nav-link:hover {
        background-color: rgba(255,255,255,0.05);
        color: white;
    }
    .side-nav .nav-link.active {
        background-color: var(--okx-blue);
        color: white;
    }
    .content-card {
        background-color: #181a20;
        border-radius: 24px;
        padding: 40px;
        border: 1px solid #2b2f36;
        height: 100%;
    }
    .stat-box {
        background: rgba(255,255,255,0.03);
        border: 1px solid #2b2f36;
        border-radius: 16px;
        padding: 25px;
        text-align: center;
    }
    .upload-area {
        border: 2px dashed #2b2f36;
        border-radius: 16px;
        padding: 30px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
    }
    .upload-area:hover {
        border-color: var(--okx-blue);
        background: rgba(0, 70, 255, 0.05);
    }
    .asset-row {
        padding: 20px 0;
        border-bottom: 1px solid #2b2f36;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .asset-row:last-child { border-bottom: none; }
    .form-control {
        background-color: #0b0e11;
        border: 1px solid #2b2f36;
        color: white;
        padding: 12px;
        border-radius: 10px;
    }
    .form-control:focus {
        background-color: #0b0e11;
        border-color: var(--okx-blue);
        color: white;
        box-shadow: none;
    }

    @media (max-width: 991px) {
        .profile-container { padding: 20px 0; }
        .content-card { padding: 25px; margin-top: 20px; }
    }
</style>

<div class="profile-container">
    <div class="container">
        <?php if ($msg): ?>
            <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" style="border-radius: 12px;">
                <?php echo $msg; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm" style="border-radius: 12px;">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <!-- Sidebar -->
            <div class="col-lg-3">
                <div class="side-nav shadow-sm">
                    <div class="text-center mb-4">
                        <div class="d-inline-block position-relative mb-3">
                            <div class="rounded-circle d-flex align-items-center justify-content-center text-white fw-bold fs-2" style="width: 80px; height: 80px; background: var(--bit-gradient);">
                                <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                            </div>
                            <span class="position-absolute bottom-0 end-0 bg-success border border-dark rounded-circle" style="width: 18px; height: 18px;"></span>
                        </div>
                        <h5 class="mb-1 text-white"><?php echo htmlspecialchars($user['username']); ?></h5>
                        <p class="small text-muted mb-0">UID: <span class="text-white"><?php echo str_pad($user['uid'], 6, '0', STR_PAD_LEFT); ?></span></p>
                    </div>
                    
                    <div class="nav flex-column" id="v-pills-tab" role="tablist">
                        <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" data-bs-target="#overview" type="button"><i class="fas fa-th-large me-2"></i> <?php echo mt('Overview'); ?></button>
                        <button class="nav-link" id="assets-tab" data-bs-toggle="pill" data-bs-target="#assets" type="button"><i class="fas fa-wallet me-2"></i> <?php echo mt('Assets'); ?></button>
                        <button class="nav-link" id="security-tab" data-bs-toggle="pill" data-bs-target="#security" type="button"><i class="fas fa-shield-alt me-2"></i> <?php echo mt('Security'); ?></button>
                        <button class="nav-link" id="kyc-tab" data-bs-toggle="pill" data-bs-target="#kyc" type="button"><i class="fas fa-user-check me-2"></i> <?php echo mt('Verification'); ?></button>
                    </div>
                </div>
            </div>

            <!-- Content -->
            <div class="col-lg-9">
                <div class="tab-content h-100 shadow-sm">
                    <!-- Overview -->
                    <div class="tab-pane fade show active" id="overview">
                        <div class="content-card">
                            <h3 class="fw-bold mb-4 text-white"><?php echo mt('Account Overview'); ?></h3>
                            <div class="row g-4 mb-5">
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="small text-muted mb-2"><?php echo mt('Total Balance'); ?></div>
                                        <h2 class="fw-bold text-white"><?php echo number_format($user['balance_usdt'], 2); ?> <span class="fs-6 text-muted">USDT</span></h2>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="small text-muted mb-2"><?php echo mt('Identity Verification'); ?></div>
                                        <h4 class="fw-bold <?php echo $user['kyc_status'] == 'approved' ? 'text-success' : 'text-warning'; ?>">
                                            <?php echo mt($user['kyc_status'] ?: 'Unverified'); ?>
                                        </h4>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-box">
                                        <div class="small text-muted mb-2"><?php echo mt('Security'); ?></div>
                                        <h4 class="fw-bold text-success">Level 2</h4>
                                    </div>
                                </div>
                            </div>
                            
                            <h5 class="fw-bold mb-3 text-white"><?php echo mt('Recent Activities'); ?></h5>
                            <div class="table-responsive">
                                <table class="table table-dark table-hover border-secondary">
                                    <thead>
                                        <tr class="text-muted small">
                                            <th><?php echo mt('Time'); ?></th>
                                            <th><?php echo mt('Action'); ?></th>
                                            <th><?php echo mt('Status'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody class="small">
                                        <tr>
                                            <td><?php echo date('Y-m-d H:i'); ?></td>
                                            <td><?php echo mt('Account Login'); ?></td>
                                            <td><span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2"><?php echo mt('Success'); ?></span></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Assets -->
                    <div class="tab-pane fade" id="assets">
                        <div class="content-card">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h3 class="fw-bold mb-0 text-white"><?php echo mt('Assets Overview'); ?></h3>
                                <div>
                                    <a href="deposit.php" class="btn btn-primary px-4 me-2 border-0" style="background: var(--okx-blue);"><?php echo mt('Deposit'); ?></a>
                                    <a href="withdraw.php" class="btn btn-outline-light px-4"><?php echo mt('Withdraw'); ?></a>
                                </div>
                            </div>
                            
                            <div class="bg-dark bg-opacity-50 p-4 rounded-4 mb-4 border border-secondary">
                                <div class="row">
                                    <div class="col-md-6 border-end border-secondary">
                                        <div class="small text-muted mb-1"><?php echo mt('Total Net Value'); ?> (USDT)</div>
                                        <h1 class="fw-bold text-white"><?php echo number_format($user['balance_usdt'], 2); ?></h1>
                                    </div>
                                    <div class="col-md-6 ps-md-4">
                                        <div class="small text-muted mb-1"><?php echo mt('Yesterday Profit/Loss'); ?></div>
                                        <h3 class="fw-bold text-success">+$0.00 (0.00%)</h3>
                                    </div>
                                </div>
                            </div>

                            <div class="asset-list">
                                <div class="asset-row">
                                    <div class="d-flex align-items-center">
                                        <img src="https://static.okx.com/cdn/oksupport/asset/currency/icon/usdt.png" width="40" class="me-3">
                                        <div>
                                            <div class="fw-bold text-white">USDT</div>
                                            <div class="small text-muted">Tether</div>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold text-white"><?php echo number_format($user['balance_usdt'], 2); ?></div>
                                        <div class="small text-muted">≈ $<?php echo number_format($user['balance_usdt'], 2); ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Security -->
                    <div class="tab-pane fade" id="security">
                        <div class="content-card">
                            <h3 class="fw-bold mb-4 text-white"><?php echo mt('Security Settings'); ?></h3>
                            
                            <div class="mb-5">
                                <div class="d-flex justify-content-between align-items-center py-4 border-bottom border-secondary">
                                    <div>
                                        <h6 class="mb-1 text-white"><?php echo mt('Login Password'); ?></h6>
                                        <p class="small text-muted mb-0"><?php echo mt('Last updated'); ?>: <?php echo mt('Recently'); ?></p>
                                    </div>
                                    <button class="btn btn-outline-light btn-sm px-4 rounded-pill" data-bs-toggle="modal" data-bs-target="#loginPassModal"><?php echo mt('Change'); ?></button>
                                </div>
                                <div class="d-flex justify-content-between align-items-center py-4 border-bottom border-secondary">
                                    <div>
                                        <h6 class="mb-1 text-white"><?php echo mt('Trading Password'); ?></h6>
                                        <p class="small text-muted mb-0"><?php echo mt('Required for withdrawals'); ?></p>
                                    </div>
                                    <button class="btn btn-outline-light btn-sm px-4 rounded-pill" data-bs-toggle="modal" data-bs-target="#secPassModal"><?php echo mt('Change'); ?></button>
                                </div>
                                <div class="d-flex justify-content-between align-items-center py-4 border-bottom border-secondary">
                                    <div>
                                        <h6 class="mb-1 text-white"><?php echo mt('2FA Authentication'); ?></h6>
                                        <p class="small text-muted mb-0"><?php echo mt('Google Authenticator'); ?></p>
                                    </div>
                                    <button class="btn btn-outline-light btn-sm px-4 rounded-pill"><?php echo mt('Link'); ?></button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- KYC -->
                    <div class="tab-pane fade" id="kyc">
                        <div class="content-card">
                            <h3 class="fw-bold mb-4 text-white"><?php echo mt('Identity Verification'); ?></h3>
                            <?php if ($user['kyc_status'] == 'pending'): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-clock fa-5x text-warning mb-4"></i>
                                    <h4 class="text-white"><?php echo mt('Reviewing...'); ?></h4>
                                    <p class="text-muted"><?php echo mt('Your identity documents are being verified by our team.'); ?></p>
                                </div>
                            <?php elseif ($user['kyc_status'] == 'approved'): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-check-circle fa-5x text-success mb-4"></i>
                                    <h4 class="text-white"><?php echo mt('Verified'); ?></h4>
                                    <p class="text-muted"><?php echo mt('Your account is fully verified for all features.'); ?></p>
                                </div>
                            <?php else: ?>
                                <form action="" method="POST">
                                    <div class="row g-4 mb-4">
                                        <div class="col-md-6">
                                            <label class="form-label text-muted small"><?php echo mt('Full Name'); ?></label>
                                            <input type="text" name="real_name" class="form-control" placeholder="<?php echo mt('Enter your real name'); ?>" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label text-muted small"><?php echo mt('ID Number'); ?></label>
                                            <input type="text" name="id_number" class="form-control" placeholder="<?php echo mt('Enter ID/Passport Number'); ?>" required>
                                        </div>
                                    </div>
                                    <div class="row g-4 mb-5">
                                        <div class="col-md-4">
                                            <div class="upload-area">
                                                <i class="fas fa-id-card fa-3x mb-3 text-muted opacity-25"></i>
                                                <div class="small text-muted"><?php echo mt('Front Side'); ?></div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="upload-area">
                                                <i class="fas fa-id-card fa-3x mb-3 text-muted opacity-25"></i>
                                                <div class="small text-muted"><?php echo mt('Back Side'); ?></div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="upload-area">
                                                <i class="fas fa-camera fa-3x mb-3 text-muted opacity-25"></i>
                                                <div class="small text-muted"><?php echo mt('Selfie with ID'); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="submit" name="kyc_submit" class="btn btn-primary w-100 py-3 fw-bold border-0" style="background: var(--okx-blue); border-radius: 16px;"><?php echo mt('Submit'); ?></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modals -->
<div class="modal fade" id="loginPassModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary" style="border-radius: 20px;">
            <div class="modal-header border-secondary p-4">
                <h5 class="modal-title text-white fw-bold"><?php echo mt('Change Login Password'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="" method="POST">
                <div class="modal-body p-4">
                    <input type="hidden" name="change_password" value="1">
                    <input type="hidden" name="type" value="login">
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('Current Password'); ?></label>
                        <input type="password" name="old_password" class="form-control shadow-none" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('New Password'); ?></label>
                        <input type="password" name="new_password" class="form-control shadow-none" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('Confirm New Password'); ?></label>
                        <input type="password" name="confirm_password" class="form-control shadow-none" required>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-secondary px-4 rounded-pill" data-bs-dismiss="modal"><?php echo mt('Cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4 rounded-pill border-0" style="background: var(--okx-blue);"><?php echo mt('Save Changes'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="secPassModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary" style="border-radius: 20px;">
            <div class="modal-header border-secondary p-4">
                <h5 class="modal-title text-white fw-bold"><?php echo mt('Change Trading Password'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="" method="POST">
                <div class="modal-body p-4">
                    <input type="hidden" name="change_password" value="1">
                    <input type="hidden" name="type" value="security">
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('Current Trading Password'); ?></label>
                        <input type="password" name="old_password" class="form-control shadow-none" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('New Trading Password'); ?> (6 <?php echo mt('digits'); ?>)</label>
                        <input type="password" name="new_password" class="form-control shadow-none" pattern="\d{6}" maxlength="6" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label text-muted small"><?php echo mt('Confirm New Trading Password'); ?></label>
                        <input type="password" name="confirm_password" class="form-control shadow-none" pattern="\d{6}" maxlength="6" required>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-secondary px-4 rounded-pill" data-bs-dismiss="modal"><?php echo mt('Cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4 rounded-pill border-0" style="background: var(--okx-blue);"><?php echo mt('Save Changes'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>