<?php
/**
 * User Profile Page
 */
$pageTitle = 'Profile';
require_once 'includes/header.php';

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

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_profile') {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        dbUpdate('users', [
            'first_name' => $firstName,
            'last_name' => $lastName,
            'phone' => $phone
        ], 'id = :id', ['id' => $user['id']]);
        
        $user['first_name'] = $firstName;
        $user['last_name'] = $lastName;
        $user['phone'] = $phone;
        $success = 'Profile updated successfully!';
        
    } elseif ($action === 'change_password') {
        $currentPass = $_POST['current_password'] ?? '';
        $newPass = $_POST['new_password'] ?? '';
        $confirmPass = $_POST['confirm_password'] ?? '';
        
        if (!password_verify($currentPass, $user['password'])) {
            $error = 'Current password is incorrect';
        } elseif (strlen($newPass) < 8) {
            $error = 'New password must be at least 8 characters';
        } elseif ($newPass !== $confirmPass) {
            $error = 'New passwords do not match';
        } else {
            $hashedPass = password_hash($newPass, PASSWORD_BCRYPT, ['cost' => 12]);
            dbUpdate('users', ['password' => $hashedPass], 'id = :id', ['id' => $user['id']]);
            $success = 'Password changed successfully!';
        }
    }
}

// Get wallet info
$wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = ?", [$user['id']]);
if (!$wallet) {
    $wallet = ['balance' => 0, 'demo_balance' => 10000, 'total_trades' => 0, 'total_won' => 0, 'total_lost' => 0];
}

// Pending withdrawals (already fetched in header.php as $pendingAmount)
$profilePending = $pendingAmount ?? 0;

// Auto-generate referral code if missing
if (empty($user['referral_code'])) {
    $newCode = strtoupper(substr(md5($user['id'] . $user['email'] . time()), 0, 8));
    dbUpdate('users', ['referral_code' => $newCode], 'id = :id', ['id' => $user['id']]);
    $user['referral_code'] = $newCode;
}
?>

<style>
.profile-grid { display: grid; grid-template-columns: 300px 1fr; gap: 1.5rem; }
@media (max-width: 992px) { .profile-grid { grid-template-columns: 1fr; } }
.profile-sidebar { text-align: center; }
.profile-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: linear-gradient(135deg, var(--accent-green), var(--accent-blue));
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    font-weight: 600;
    color: white;
    margin: 0 auto 1rem;
}
.profile-name { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.25rem; }
.profile-email { color: var(--text-muted); font-size: 0.9rem; }
.profile-stats { margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border-color); }
.profile-stat { display: flex; justify-content: space-between; padding: 0.5rem 0; }
.profile-stat-label { color: var(--text-muted); }
.profile-stat-value { font-weight: 600; }
.kyc-status {
    margin-top: 1rem;
    padding: 0.75rem;
    border-radius: var(--radius-md);
    text-align: center;
}
.kyc-status.pending { background: rgba(251, 191, 36, 0.1); color: var(--accent-yellow); }
.kyc-status.verified { background: rgba(0, 208, 156, 0.1); color: var(--accent-green); }
.kyc-status.unverified { background: rgba(255, 82, 82, 0.1); color: var(--accent-red); }
.kyc-status.rejected { background: rgba(255, 82, 82, 0.1); color: var(--accent-red); }
.tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; border-bottom: 1px solid var(--border-color); padding-bottom: 0.5rem; }
.tab-btn {
    padding: 0.5rem 1rem;
    background: transparent;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    border-radius: var(--radius-md);
}
.tab-btn:hover { color: var(--text-primary); }
.tab-btn.active { background: var(--bg-tertiary); color: var(--accent-green); }
.tab-content { display: none; }
.tab-content.active { display: block; }
</style>

<?php if ($error): ?>
<div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?= $success ?></div>
<?php endif; ?>



<div class="profile-grid">
    <div>
        <div class="card">
            <div class="card-body profile-sidebar">
                <div class="profile-avatar">
                    <?= strtoupper(substr($user['first_name'] ?? $user['email'], 0, 1)) ?>
                </div>
                <div class="profile-name"><?= htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')) ?></div>
                <div class="profile-email"><?= htmlspecialchars($user['email']) ?></div>
                
                <div class="kyc-status <?= ($user['kyc_status'] ?? '') === 'submitted' ? 'pending' : ($user['kyc_status'] ?? 'unverified') ?>">
                    <?php if (($user['kyc_status'] ?? '') === 'verified'): ?>
                        <i class="fas fa-check-circle"></i> KYC Verified
                    <?php elseif (($user['kyc_status'] ?? '') === 'submitted'): ?>
                        <i class="fas fa-clock"></i> KYC Pending
                    <?php elseif (($user['kyc_status'] ?? '') === 'rejected'): ?>
                        <i class="fas fa-times-circle"></i> KYC Rejected
                    <?php else: ?>
                        <i class="fas fa-exclamation-circle"></i> KYC Not Verified
                    <?php endif; ?>
                </div>
                
                <div class="profile-stats">
                    <div class="profile-stat">
                        <span class="profile-stat-label">User ID</span>
                        <span class="profile-stat-value"><?= $user['user_id'] ?></span>
                    </div>
                    <div class="profile-stat">
                        <span class="profile-stat-label">Real Balance</span>
                        <span class="profile-stat-value text-green"><?= formatCurrency(max(0, ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - $profilePending)) ?></span>
                    </div>
                    <div class="profile-stat">
                        <span class="profile-stat-label">Demo Balance</span>
                        <span class="profile-stat-value"><?= formatCurrency(($wallet['demo_balance'] ?? 10000)) ?></span>
                    </div>
                    <div class="profile-stat">
                        <span class="profile-stat-label">Total Trades</span>
                        <span class="profile-stat-value"><?= number_format($wallet['total_trades'] ?? 0) ?></span>
                    </div>
                    <div class="profile-stat">
                        <span class="profile-stat-label">Member Since</span>
                        <span class="profile-stat-value"><?= formatDateTime($user['created_at'], 'd M Y') ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div>
        <div class="card">
            <div class="card-body">
                <div class="tabs">
                    <button class="tab-btn active" onclick="showTab('profile')">Profile</button>
                    <button class="tab-btn" onclick="showTab('security')">Security</button>
                    <button class="tab-btn" onclick="showTab('kyc')">KYC</button>
                </div>
                
                <!-- Profile Tab -->
                <div class="tab-content active" id="profileTab">
                    <form method="POST">
                        <input type="hidden" name="action" value="update_profile">
                        
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">First Name</label>
                                <input type="text" name="first_name" class="form-control" value="<?= htmlspecialchars($user['first_name'] ?? '') ?>">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Last Name</label>
                                <input type="text" name="last_name" class="form-control" value="<?= htmlspecialchars($user['last_name'] ?? '') ?>">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" value="<?= htmlspecialchars($user['email']) ?>" disabled>
                            <div class="form-text">Email cannot be changed</div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Phone Number</label>
                            <input type="tel" name="phone" class="form-control" value="<?= htmlspecialchars($user['phone'] ?? '') ?>" placeholder="+91 9876543210">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Referral Code</label>
                            <div class="d-flex gap-2">
                                <input type="text" class="form-control" value="<?= $user['referral_code'] ?>" readonly>
                                <button type="button" class="btn btn-secondary" onclick="copyText('<?= $user['referral_code'] ?>')">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <div class="form-text">Share this code to earn referral bonus</div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Changes
                        </button>
                    </form>
                </div>
                
                <!-- Security Tab -->
                <div class="tab-content" id="securityTab">
                    <h4 style="margin-bottom: 1rem;">Change Password</h4>
                    <form method="POST">
                        <input type="hidden" name="action" value="change_password">
                        
                        <div class="form-group">
                            <label class="form-label">Current Password</label>
                            <input type="password" name="current_password" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">New Password</label>
                            <input type="password" name="new_password" class="form-control" minlength="8" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Confirm New Password</label>
                            <input type="password" name="confirm_password" class="form-control" minlength="8" required>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-lock"></i> Change Password
                        </button>
                    </form>
                </div>
                
                <!-- KYC Tab -->
                <div class="tab-content" id="kycTab">
                    <?php $kycStatus = $user['kyc_status'] ?? ''; ?>
                    <?php if ($kycStatus === 'verified'): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-check-circle text-green" style="font-size: 4rem;"></i>
                        <h3 style="margin: 1rem 0;">KYC Verified</h3>
                        <p class="text-muted">Your identity has been verified. You have full access to all features.</p>
                    </div>
                    <?php elseif ($kycStatus === 'submitted'): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-clock text-yellow" style="font-size: 4rem;"></i>
                        <h3 style="margin: 1rem 0;">Verification Pending</h3>
                        <p class="text-muted">Your documents are under review. This usually takes 24-48 hours.</p>
                    </div>
                    <?php else: ?>
                    <!-- Show KYC upload form for: unverified (empty), rejected, or any other status -->
                    <div id="kycForm">
                        <?php if ($kycStatus === 'rejected'): ?>
                        <div class="alert alert-danger" style="margin-bottom: 1rem;">
                            <i class="fas fa-times-circle"></i> Your KYC was rejected. Please re-submit your documents.
                        </div>
                        <?php endif; ?>
                        <p class="text-muted mb-3">Complete KYC verification to unlock higher withdrawal limits.</p>
                        <form method="POST" enctype="multipart/form-data" action="kyc-submit.php">
                            <div class="form-group">
                                <label class="form-label">Document Type</label>
                                <select name="document_type" class="form-control" required>
                                    <option value="">Select document</option>
                                    <option value="aadhar">Aadhaar Card</option>
                                    <option value="pan">PAN Card</option>
                                    <option value="passport">Passport</option>
                                    <option value="driving_license">Driving License</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Document Number</label>
                                <input type="text" name="document_number" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Front Side Photo</label>
                                <input type="file" name="front_image" class="form-control" accept="image/*" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Back Side Photo (if applicable)</label>
                                <input type="file" name="back_image" class="form-control" accept="image/*">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Selfie with Document</label>
                                <input type="file" name="selfie_image" class="form-control" accept="image/*" required>
                                <div class="form-text">Take a selfie while holding your ID document</div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload"></i> Submit for Verification
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function showTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    
    document.querySelector(`[onclick="showTab('${tab}')"]`).classList.add('active');
    document.getElementById(tab + 'Tab').classList.add('active');
}

function copyText(text) {
    navigator.clipboard.writeText(text);
    showToast('Copied!', 'success');
}


</script>

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