<?php
require_once 'db.php'; // centralized PDO connection
session_start();

// Redirect if not logged in or session expired
if (!isset($_SESSION['user_id']) || (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 600))) {
    if (isset($_SESSION['user_id'])) unset($_SESSION['user_id']);
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header("Location: login.php");
    exit();
}
$_SESSION['last_activity'] = time();

$userId = $_SESSION['user_id'];

// Fetch user info
$stmt = $conn->prepare("SELECT firstName, lastName, email, phone, profile_pic, is_admin FROM users WHERE id = :id");
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $user['firstName'] ?? '';
$lastName = $user['lastName'] ?? '';
$email = $user['email'] ?? '';
$phone = $user['phone'] ?? '';
$profilePic = $user['profile_pic'] ?? '';
$isAdmin = $user['is_admin'] ?? 0;

// Fetch user measurements
$stmt = $conn->prepare("SELECT chest, waist, hips, bust, shoulders, gender FROM measurements WHERE user_id = :id");
$stmt->execute(['id' => $userId]);
$meas = $stmt->fetch(PDO::FETCH_ASSOC);
$chest = $meas['chest'] ?? '';
$waist = $meas['waist'] ?? '';
$hips = $meas['hips'] ?? '';
$bust = $meas['bust'] ?? '';
$shoulders = $meas['shoulders'] ?? '';
$gender = $meas['gender'] ?? '';

$displayName = trim($firstName . ' ' . $lastName);

// Helper to display value or placeholder
function displayOrPlaceholder($value, $placeholder, $isMeasurement = false) {
    if (!empty($value)) return htmlspecialchars($value) . ($isMeasurement ? " cm" : "");
    return "<span class='placeholder'>$placeholder</span>";
}

// Cart count
$cart_count = 0;
if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $item) $cart_count += $item['quantity'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Profile - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="admin-sidebar.css">
<style>
body { margin:0; font-family:'Segoe UI',sans-serif; background:#000; color:#fff; position:relative; }
#particles-js { position:fixed; top:0; left:0; width:100%; height:100%; z-index:0; pointer-events:none; }

a { text-decoration:none; }

.dashboard-wrapper { display:flex; flex-direction:column; min-height:100vh; z-index:2; position:relative; }
.dashboard-inner { display:flex; flex:1; }

.main-content { flex:1; padding:20px; background:#111; margin-left:250px; }
.container { max-width:900px; margin:0 auto; background:#1a1a1a; padding:25px; border-radius:12px; box-shadow:0 4px 20px rgba(0,0,0,0.5); }
h1 { text-align:center; margin-bottom:25px; font-size:1.8rem; color:#f0f0f0; }

.profile-wrapper { display:flex; flex-wrap:wrap; gap:25px; }
.profile-left, .profile-right { flex:1; min-width:250px; }
.profile-pic { text-align:center; margin-bottom:20px; }
.profile-pic img { width:120px; height:120px; object-fit:cover; border-radius:50%; border:3px solid #888; cursor:pointer; transition:transform 0.3s; }
.profile-pic img:hover { transform:scale(1.05); }
.info-group { margin-bottom:15px; }
.info-group label { font-weight:600; display:block; margin-bottom:5px; font-size:14px; color:#bbb; }
.info-group p, .info-group a { margin:0; display:inline-block; background:#2a2a2a; padding:10px 12px; border-radius:6px; font-size:14px; color:#f5f5f5; }
.placeholder { color:#777; background:#333; cursor:not-allowed; }

.actions { text-align:center; margin-top:25px; }
.actions a { background:#333; color:#fff; padding:10px 18px; margin:0 8px; border-radius:8px; transition:background 0.3s; }
.actions a:hover { background:#555; }

@media(max-width:768px) {
  .profile-wrapper { flex-direction:column; }
  .profile-pic img { width:100px; height:100px; }
  .main-content { margin-left:0; }
}
</style>
</head>
<body>

<div id="particles-js"></div>
<?php include "navbar.php"; ?>
<div class="dashboard-wrapper">
    <?php if ($isAdmin == 1) include "admin-sidebar.php"; ?>
    <div class="dashboard-inner">
        <div class="main-content">
            <div class="container">
                <h1>My Profile</h1>
                <div class="profile-pic">
                    <form action="upload-profile-pic.php" method="post" enctype="multipart/form-data" id="picForm">
                        <input type="file" name="profile_pic" id="fileInput" style="display:none" onchange="document.getElementById('picForm').submit()">
                        <label for="fileInput">
                            <img src="<?= $profilePic ? htmlspecialchars($profilePic) : 'images/default-user.png' ?>" alt="Profile Picture">
                        </label>
                    </form>
                    <p style="font-size:13px;color:#777;margin-top:8px;">Click picture to change</p>
                </div>

                <div class="profile-wrapper">
                    <div class="profile-left">
                        <div class="info-group"><label>First Name:</label><p><?= displayOrPlaceholder($firstName, "Add your first name") ?></p></div>
                        <div class="info-group"><label>Last Name:</label><p><?= displayOrPlaceholder($lastName, "Add your last name") ?></p></div>
                        <div class="info-group"><label>Email:</label><p><?= displayOrPlaceholder($email, "Add your email") ?></p></div>
                        <div class="info-group"><label>Phone:</label><p><?= displayOrPlaceholder($phone, "Add your phone number") ?></p></div>
                    </div>
                    <div class="profile-right">
                        <h3 style="margin-top:0;color:#ddd;">Measurements</h3>
                        <div class="info-group"><label>Gender:</label><p><?= displayOrPlaceholder($gender, "Add your gender") ?></p></div>
                        <div class="info-group"><label>Chest:</label><p><?= displayOrPlaceholder($chest, "Add your chest measurement", true) ?></p></div>
                        <div class="info-group"><label>Waist:</label><p><?= displayOrPlaceholder($waist, "Add your waist measurement", true) ?></p></div>
                        <div class="info-group"><label>Shoulders:</label><p><?= displayOrPlaceholder($shoulders, "Add your shoulder measurement", true) ?></p></div>
                        <div class="info-group"><label>Bust:</label><p><?= displayOrPlaceholder($bust, "Add your bust measurement", true) ?></p></div>
                    </div>
                </div>

                <div class="actions">
                    <a href="edit-profile.php">Edit Profile</a>
                    <a href="edit-measurements.php">Edit Measurements</a>
                    <a href="logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
<script>
// Initialize white particle background
particlesJS("particles-js", {
  "particles": {
    "number":{"value":80,"density":{"enable":true,"value_area":800}},
    "color":{"value":"#ffffff"},
    "shape":{"type":"circle"},
    "opacity":{"value":0.8,"random":true,"anim":{"enable":true,"speed":1,"opacity_min":0.1,"sync":false}},
    "size":{"value":2,"random":true,"anim":{"enable":true,"speed":4,"size_min":0.1,"sync":false}},
    "move":{"enable":true,"speed":0.3,"direction":"top","random":true,"straight":false,"out_mode":"out","bounce":false}
  },
  "interactivity":{"events":{"onhover":{"enable":false},"onclick":{"enable":false}},"modes":{}},
  "retina_detect":true
});

// Cart count
function updateCartCount() {
    fetch('get_cart.php')
    .then(res => res.json())
    .then(data => {
        const cart = data.cart || [];
        document.querySelector('.cart-badge').textContent = cart.reduce((sum,item)=>sum+parseInt(item.quantity||0),0);
    });
}
updateCartCount();
</script>

<?php include "footer.php"; ?>
</body>
</html>
