<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require_once 'db.php';

$user_id = $_SESSION['user_id'];
$upload_message = '';
$upload_error = '';

// Handle profile picture upload
if (isset($_POST['upload_picture'])) {
    $target_dir = "uploads/profile_pictures/";
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);

    $file = $_FILES['profile_picture'];
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $new_filename = "profile_" . $user_id . "_" . time() . "." . $file_extension;
    $target_file  = $target_dir . $new_filename;
    $allowed_types = ['jpg','jpeg','png','gif'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $upload_error = "Error uploading file";
    } elseif (!in_array($file_extension, $allowed_types)) {
        $upload_error = "Only JPG, JPEG, PNG & GIF files are allowed";
    } elseif ($file['size'] > 5 * 1024 * 1024) {
        $upload_error = "File too large. Maximum 5MB";
    } elseif (!getimagesize($file['tmp_name'])) {
        $upload_error = "Not a valid image";
    } else {
        $old = mysqli_fetch_assoc(mysqli_query($conn, "SELECT profile_picture FROM users WHERE id='$user_id'"));
        if ($old && !empty($old['profile_picture']) && file_exists($old['profile_picture'])) unlink($old['profile_picture']);

        if (move_uploaded_file($file['tmp_name'], $target_file)) {
            mysqli_query($conn, "UPDATE users SET profile_picture='$target_file' WHERE id='$user_id'");
            $upload_message = "Profile picture updated successfully";
        } else {
            $upload_error = "Failed to upload file";
        }
    }
}

// Handle remove picture
if (isset($_POST['remove_picture'])) {
    $pic = mysqli_fetch_assoc(mysqli_query($conn, "SELECT profile_picture FROM users WHERE id='$user_id'"));
    if ($pic && !empty($pic['profile_picture']) && file_exists($pic['profile_picture'])) unlink($pic['profile_picture']);
    mysqli_query($conn, "UPDATE users SET profile_picture=NULL WHERE id='$user_id'");
    $upload_message = "Profile picture removed";
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Get user data
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE id='$user_id'"));

// Stats
$total_deposits    = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM deposits WHERE user_id='$user_id' AND status='processed'"))['t'] ?? 0;
$total_withdrawals = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM withdrawals WHERE user_id='$user_id' AND status='processed'"))['t'] ?? 0;
$total_profits     = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM profits WHERE user_id='$user_id'"))['t'] ?? 0;
$account_balance   = $user['balance'] ?? 0;
$referral_earnings = $user['total_referral_earnings'] ?? 0;

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile - MaxTrade</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
* { margin:0; padding:0; box-sizing:border-box; }

body {
    background:#0a0a0a;
    color:#fff;
    font-family:Arial,sans-serif;
    padding-bottom:80px;
}

/* ── HERO BANNER ── */
.hero {
    background: #111;
    padding: 28px 16px 60px;
    text-align: center;
    position: relative;
    border-bottom: 1px solid #222;
}
.hero::after {
    content:'';
    position:absolute;
    bottom:-1px; left:0; right:0;
    height:30px;
    background:#0a0a0a;
    border-radius:30px 30px 0 0;
}

/* Profile picture */
.avatar-wrap {
    position: relative;
    width: 88px;
    height: 88px;
    margin: 0 auto 12px;
}
.avatar {
    width: 88px;
    height: 88px;
    border-radius: 50%;
    border: 3px solid #00c853;
    background: #111;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 38px;
    overflow: hidden;
    box-shadow: 0 0 0 4px rgba(0,200,83,0.15);
}
.avatar img { width:100%; height:100%; object-fit:cover; border-radius:50%; }
.avatar-edit {
    position:absolute;
    bottom:0; right:0;
    width:26px; height:26px;
    background:#00c853;
    border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    cursor:pointer;
    font-size:11px; color:#000;
    box-shadow:0 2px 8px rgba(0,0,0,0.4);
}
.avatar-edit input { position:absolute; opacity:0; width:100%; height:100%; cursor:pointer; }

.profile-name {
    font-size:17px;
    font-weight:800;
    color:#FFD700;
    margin-bottom:3px;
}
.profile-phone {
    font-size:11px;
    color:#FFD700;
    margin-bottom:4px;
}
.profile-since {
    font-size:10px;
    color:#aaa;
}
.member-badge {
    display:inline-block;
    background:rgba(255,215,0,0.1);
    border:1px solid rgba(255,215,0,0.3);
    color:#FFD700;
    font-size:9px;
    font-weight:700;
    padding:3px 10px;
    border-radius:20px;
    margin-top:6px;
    letter-spacing:1px;
    text-transform:uppercase;
}

/* ── ALERTS ── */
.alert {
    margin:10px 12px 0;
    padding:10px 14px;
    border-radius:8px;
    font-size:12px;
    display:flex; align-items:center; gap:8px;
}
.alert-success { background:#0d2e0d; border:1px solid #1a5c1a; color:#4ade80; }
.alert-error   { background:#2e0d0d; border:1px solid #5c1a1a; color:#f87171; }

/* ── STATS ROW ── */
.stats-wrap {
    margin: -28px 12px 0;
    position: relative;
    z-index: 1;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 7px;
}
.stat-card {
    background:#111;
    border:1px solid #1e1e1e;
    border-radius:11px;
    padding:11px 6px;
    text-align:center;
}
.stat-icon { font-size:13px; margin-bottom:4px; }
.stat-val  { font-size:12px; font-weight:800; color:#fff; }
.stat-cur  { font-size:8px; color:#aaa; }
.stat-lbl  { font-size:8px; color:#888; margin-top:2px; text-transform:uppercase; letter-spacing:0.5px; }

/* ── SECTION TITLE ── */
.sec-title {
    font-size:9px;
    font-weight:700;
    color:#FFD700;
    letter-spacing:1.5px;
    text-transform:uppercase;
    padding:14px 12px 6px;
    display:flex; align-items:center; gap:5px;
}

/* ── INFO CARD ── */
.info-card {
    margin:0 12px;
    background:#111;
    border-radius:12px;
    overflow:hidden;
    border:1px solid #1a1a1a;
}
.info-row {
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:12px 14px;
    border-bottom:1px solid #161616;
}
.info-row:last-child { border-bottom:none; }
.info-left { display:flex; align-items:center; gap:10px; }
.info-icon-wrap {
    width:32px; height:32px;
    border-radius:9px;
    display:flex; align-items:center; justify-content:center;
    font-size:13px;
    background:rgba(0,200,83,0.1);
    color:#00c853;
    flex-shrink:0;
}
.info-label { font-size:10px; color:#888; margin-bottom:2px; }
.info-val   { font-size:12px; font-weight:600; color:#fff; }
.info-arrow { font-size:11px; color:#333; }

/* ── MENU LIST ── */
.menu-card {
    margin:0 12px;
    background:#111;
    border-radius:12px;
    overflow:hidden;
    border:1px solid #1a1a1a;
}
.menu-item {
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:13px 14px;
    border-bottom:1px solid #161616;
    text-decoration:none;
    color:#fff;
    transition:background 0.15s;
}
.menu-item:last-child { border-bottom:none; }
.menu-item:hover { background:#161616; }
.menu-left { display:flex; align-items:center; gap:11px; }
.menu-icon-wrap {
    width:32px; height:32px;
    border-radius:9px;
    display:flex; align-items:center; justify-content:center;
    font-size:14px;
    flex-shrink:0;
}
.menu-label { font-size:12px; font-weight:600; color:#fff; }
.menu-sub   { font-size:9px; color:#888; margin-top:1px; }
.menu-chevron { font-size:11px; color:#333; }

/* WhatsApp green */
.ic-whatsapp { background:rgba(37,211,102,0.12); color:#25d366; }
/* History */
.ic-history  { background:rgba(0,200,83,0.1); color:#00c853; }
/* Settings */
.ic-settings { background:rgba(0,200,83,0.1); color:#00c853; }
/* Support */
.ic-support  { background:rgba(0,200,83,0.1); color:#00c853; }




/* ── LOGOUT ── */
.logout-btn {
    display:flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    width:calc(100% - 24px);
    margin:0 12px;
    padding:13px;
    background:linear-gradient(135deg,#1a0000,#3d0000);
    color:#f87171;
    border:1px solid rgba(248,113,113,0.25);
    border-radius:12px;
    font-weight:700;
    cursor:pointer;
    font-size:13px;
    transition:background 0.2s;
}
.logout-btn:hover { background:linear-gradient(135deg,#2a0000,#5c0000); }

/* ── REMOVE PIC ── */
.remove-pic-btn {
    display:inline-flex; align-items:center; gap:5px;
    background:rgba(248,113,113,0.1);
    border:1px solid rgba(248,113,113,0.25);
    color:#f87171;
    padding:5px 12px;
    border-radius:6px;
    cursor:pointer;
    font-size:10px;
    margin-top:6px;
}

/* ── MODAL ── */
.modal {
    display:none;
    position:fixed; z-index:1000;
    left:0; top:0; width:100%; height:100%;
    background:rgba(0,0,0,0.88);
}
.modal-box {
    background:#111;
    margin:18% auto;
    padding:20px;
    border-radius:14px;
    width:90%; max-width:340px;
    border:1px solid #222;
    box-shadow:0 8px 40px rgba(0,0,0,0.5);
}
.modal-hdr {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:14px;
}
.modal-title { font-size:14px; font-weight:700; color:#FFD700; }
.modal-close { font-size:22px; color:#aaa; cursor:pointer; }
.modal-close:hover { color:#fff; }
.file-drop {
    border:2px dashed #333;
    border-radius:9px;
    padding:20px;
    text-align:center;
    cursor:pointer;
    transition:border-color 0.2s;
    position:relative;
}
.file-drop:hover { border-color:#00c853; }
.file-drop input { position:absolute; opacity:0; inset:0; cursor:pointer; }
.file-drop i { font-size:24px; color:#00c853; margin-bottom:8px; display:block; }
.file-drop p { font-size:12px; color:#fff; }
.file-drop small { font-size:10px; color:#888; }
.preview-img { max-width:100%; max-height:160px; border-radius:8px; margin:10px auto; display:block; }
.upload-btn {
    width:100%; padding:11px;
    background:#FFD700; color:#000;
    border:none; border-radius:8px;
    font-weight:700; cursor:pointer;
    font-size:13px; margin-top:10px;
    display:flex; align-items:center; justify-content:center; gap:6px;
}
.upload-btn:hover { background:#FFA500; }
.upload-btn:disabled { background:#1a3d1a; color:#555; cursor:not-allowed; }
</style>
</head>
<body>

<!-- HERO BANNER -->
<div class="hero">
    <div class="avatar-wrap">
        <div class="avatar">
            <?php if (!empty($user['profile_picture']) && file_exists($user['profile_picture'])): ?>
                <img src="<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile">
            <?php else: ?>
                <i class="fas fa-user" style="font-size:34px;color:#00c853;"></i>
            <?php endif; ?>
        </div>
        <div class="avatar-edit" onclick="openModal()">
            <i class="fas fa-camera"></i>
        </div>
    </div>
    <div class="profile-name"><?php echo htmlspecialchars($user['phone_number']); ?></div>
    <div class="profile-phone"><i class="fas fa-envelope" style="font-size:9px;margin-right:4px;"></i><?php echo htmlspecialchars($user['email']); ?></div>
    <div class="profile-since">Member since <?php echo date('M Y', strtotime($user['created_at'])); ?></div>
    <span class="member-badge"><i class="fas fa-shield-alt" style="margin-right:4px;"></i>Verified Member</span>
    <?php if (!empty($user['profile_picture']) && file_exists($user['profile_picture'])): ?>
    <form method="POST" style="margin-top:8px;" onsubmit="return confirm('Remove profile picture?')">
        <button type="submit" name="remove_picture" class="remove-pic-btn">
            <i class="fas fa-trash-alt"></i> Remove Photo
        </button>
    </form>
    <?php endif; ?>
</div>

<?php if ($upload_message): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i><?php echo $upload_message; ?></div>
<?php endif; ?>
<?php if ($upload_error): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i><?php echo $upload_error; ?></div>
<?php endif; ?>

<!-- STATS -->
<div class="stats-wrap">
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="color:#00c853;"><i class="fas fa-wallet"></i></div>
            <div class="stat-val"><span class="stat-cur">ZMW </span><?php echo number_format($account_balance, 0); ?></div>
            <div class="stat-lbl">Balance</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="color:#00c853;"><i class="fas fa-arrow-circle-down"></i></div>
            <div class="stat-val"><span class="stat-cur">ZMW </span><?php echo number_format($total_deposits, 0); ?></div>
            <div class="stat-lbl">Deposited</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="color:#00c853;"><i class="fas fa-coins"></i></div>
            <div class="stat-val"><span class="stat-cur">ZMW </span><?php echo number_format($total_profits, 0); ?></div>
            <div class="stat-lbl">Profits</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="color:#00c853;"><i class="fas fa-arrow-circle-up"></i></div>
            <div class="stat-val"><span class="stat-cur">ZMW </span><?php echo number_format($total_withdrawals, 0); ?></div>
            <div class="stat-lbl">Withdrawn</div>
        </div>

    </div>
</div>

<!-- ACCOUNT INFO -->
<div class="sec-title"><i class="fas fa-id-card"></i> Account Info</div>
<div class="info-card">
    <div class="info-row">
        <div class="info-left">
            <div class="info-icon-wrap"><i class="fas fa-phone"></i></div>
            <div>
                <div class="info-label">Phone Number</div>
                <div class="info-val"><?php echo htmlspecialchars($user['phone_number']); ?></div>
            </div>
        </div>
    </div>
    <div class="info-row">
        <div class="info-left">
            <div class="info-icon-wrap"><i class="fas fa-envelope"></i></div>
            <div>
                <div class="info-label">Email Address</div>
                <div class="info-val"><?php echo htmlspecialchars($user['email']); ?></div>
            </div>
        </div>
    </div>
    <div class="info-row">
        <div class="info-left">
            <div class="info-icon-wrap"><i class="fas fa-calendar-alt"></i></div>
            <div>
                <div class="info-label">Member Since</div>
                <div class="info-val"><?php echo date('F d, Y', strtotime($user['created_at'])); ?></div>
            </div>
        </div>
    </div>
</div>



<!-- MENU -->
<div class="sec-title"><i class="fas fa-th-list"></i> Quick Links</div>
<div class="menu-card">

    <a href="https://chat.whatsapp.com/INGLEDlIqMILWCeT2zvVMz" target="_blank" class="menu-item">
        <div class="menu-left">
            <div class="menu-icon-wrap ic-whatsapp"><i class="fab fa-whatsapp"></i></div>
            <div>
                <div class="menu-label">WhatsApp Community</div>
                <div class="menu-sub">Join our official group for updates</div>
            </div>
        </div>
        <i class="fas fa-chevron-right menu-chevron"></i>
    </a>

    <a href="transactionhistory.php" class="menu-item">
        <div class="menu-left">
            <div class="menu-icon-wrap ic-history"><i class="fas fa-history"></i></div>
            <div>
                <div class="menu-label">Transaction History</div>
                <div class="menu-sub">View all deposits & withdrawals</div>
            </div>
        </div>
        <i class="fas fa-chevron-right menu-chevron"></i>
    </a>


    <a href="settings.php" class="menu-item">
        <div class="menu-left">
            <div class="menu-icon-wrap ic-settings"><i class="fas fa-cog"></i></div>
            <div>
                <div class="menu-label">Settings</div>
                <div class="menu-sub">Change password & preferences</div>
            </div>
        </div>
        <i class="fas fa-chevron-right menu-chevron"></i>
    </a>

    <a href="https://tawk.to/chat/6387ade9b0d6371309d1fc07/default" target="_blank" class="menu-item">
        <div class="menu-left">
            <div class="menu-icon-wrap ic-support"><i class="fas fa-headset"></i></div>
            <div>
                <div class="menu-label">Live Support</div>
                <div class="menu-sub">Chat with our support team</div>
            </div>
        </div>
        <i class="fas fa-chevron-right menu-chevron"></i>
    </a>

</div>

<!-- LOGOUT -->
<br>
<button class="logout-btn" onclick="if(confirm('Are you sure you want to logout?')) window.location.href='?logout=1'">
    <i class="fas fa-sign-out-alt"></i> Logout
</button>
<br>

<!-- UPLOAD MODAL -->
<div id="uploadModal" class="modal">
    <div class="modal-box">
        <div class="modal-hdr">
            <span class="modal-title"><i class="fas fa-camera" style="margin-right:6px;"></i>Update Photo</span>
            <span class="modal-close" onclick="closeModal()">&times;</span>
        </div>
        <form method="POST" enctype="multipart/form-data" id="uploadForm">
            <div class="file-drop" onclick="document.getElementById('fileInput').click()">
                <input type="file" name="profile_picture" id="fileInput" accept="image/*" onchange="previewImage(this)" required>
                <i class="fas fa-cloud-upload-alt"></i>
                <p id="dropText">Tap to select photo</p>
                <small>JPG, PNG, GIF — Max 5MB</small>
            </div>
            <img id="imgPreview" class="preview-img" style="display:none;">
            <button type="submit" name="upload_picture" class="upload-btn" id="uploadBtn" disabled>
                <i class="fas fa-check"></i> Save Photo
            </button>
        </form>
    </div>
</div>

<script>
function openModal() { document.getElementById('uploadModal').style.display='block'; }
function closeModal() {
    document.getElementById('uploadModal').style.display='none';
    document.getElementById('uploadForm').reset();
    document.getElementById('imgPreview').style.display='none';
    document.getElementById('uploadBtn').disabled=true;
    document.getElementById('dropText').textContent='Tap to select photo';
}
function previewImage(input) {
    if (input.files && input.files[0]) {
        const r = new FileReader();
        r.onload = e => {
            const img = document.getElementById('imgPreview');
            img.src = e.target.result;
            img.style.display = 'block';
            document.getElementById('uploadBtn').disabled = false;
            document.getElementById('dropText').textContent = '✓ Photo selected';
        };
        r.readAsDataURL(input.files[0]);
    }
}

function toast(msg) {
    const el = document.createElement('div');
    el.style.cssText = 'position:fixed;bottom:90px;left:50%;transform:translateX(-50%);background:#FFD700;color:#000;padding:10px 20px;border-radius:20px;font-size:12px;font-weight:700;z-index:9999;';
    el.textContent = msg;
    document.body.appendChild(el);
    setTimeout(() => { el.style.transition='opacity .3s'; el.style.opacity='0'; setTimeout(()=>el.remove(),300); }, 2000);
}
window.onclick = e => { if(e.target===document.getElementById('uploadModal')) closeModal(); };
setTimeout(() => {
    document.querySelectorAll('.alert').forEach(a => {
        a.style.transition='opacity .5s'; a.style.opacity='0';
        setTimeout(()=>a.remove(),500);
    });
}, 4000);
document.querySelector('.nav-item[href="profile.php"]')?.classList.add('active');
</script>
<?php include 'bottom-nav.php'; ?>

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/6995198798996e1c3b7537e0/1jhn6nepa';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

<style>
/* Force Tawk widget to middle-right of screen */
#tawkchat-container,
.tawk-min-container,
.tawk-button-container,
iframe[title*="chat"],
iframe[src*="tawk"] {
    position: fixed !important;
    top: 50% !important;
    right: 0px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;
    z-index: 9999 !important;
}
</style>

<script>
// Use Tawk API to reposition widget after load
if (typeof Tawk_API !== 'undefined') {
    Tawk_API.onLoad = function() {
        // Hide default launcher and use custom positioning
        var style = document.createElement('style');
        style.innerHTML = [
            'iframe[title*="Tawk"], iframe[src*="tawk.to"] {',
            '    position: fixed !important;',
            '    top: 50% !important;',
            '    right: 0 !important;',
            '    bottom: auto !important;',
            '    transform: translateY(-50%) !important;',
            '    z-index: 99999 !important;',
            '}'
        ].join('');
        document.head.appendChild(style);
    };
}
</script>

</body>
</html>