<?php
session_start();
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");

// Redirect if not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];

// Check if form submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get POST data and sanitize
    $gender    = trim($_POST['gender'] ?? '');
    $chest     = trim($_POST['chest'] ?? '');
    $waist     = trim($_POST['waist'] ?? '');
    $shoulders = trim($_POST['shoulders'] ?? '');
    $bust      = trim($_POST['bust'] ?? '');

    // Optional: validate numbers
    $chest     = is_numeric($chest) ? $chest : null;
    $waist     = is_numeric($waist) ? $waist : null;
    $shoulders = is_numeric($shoulders) ? $shoulders : null;
    $bust      = is_numeric($bust) ? $bust : null;

    // Check if user already has measurements
    $stmt = $conn->prepare("SELECT COUNT(*) FROM measurements WHERE user_id=?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    if ($count > 0) {
        // Update existing measurements
        $stmt = $conn->prepare("UPDATE measurements SET gender=?, chest=?, waist=?, shoulders=?, bust=? WHERE user_id=?");
        $stmt->bind_param("sddddi", $gender, $chest, $waist, $shoulders, $bust, $userId);
        $stmt->execute();
        $stmt->close();
    } else {
        // Insert new measurements
        $stmt = $conn->prepare("INSERT INTO measurements (user_id, gender, chest, waist, shoulders, bust) VALUES (?,?,?,?,?,?)");
        $stmt->bind_param("isdddd", $userId, $gender, $chest, $waist, $shoulders, $bust);
        $stmt->execute();
        $stmt->close();
    }
}

// Close connection
$conn->close();

// Redirect back to profile page
header("Location: profile.php");
exit();
