<?php
session_start();
include '../db_connect.php';

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

$user_id = $_SESSION['user_id'];

// Get form inputs
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name  = mysqli_real_escape_string($conn, $_POST['last_name']);
$address    = mysqli_real_escape_string($conn, $_POST['address']);
$city       = mysqli_real_escape_string($conn, $_POST['city']);
$state      = mysqli_real_escape_string($conn, $_POST['state']);
$email      = mysqli_real_escape_string($conn, $_POST['email']);
$phone      = mysqli_real_escape_string($conn, $_POST['phone']);

// Handle profile picture upload
$profile_pic = '';
if (!empty($_FILES['profile_pic']['name'])) {
    $target_dir = "../uploads/";
    $file_name = time() . "_" . basename($_FILES["profile_pic"]["name"]);
    $target_file = $target_dir . $file_name;

    if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file)) {
        $profile_pic = $file_name;
    }
}

// Update query
if ($profile_pic) {
    $query = "UPDATE users 
              SET first_name='$first_name', last_name='$last_name', address='$address', 
                  city='$city', state='$state', email='$email', phone='$phone', 
                  profile_pic='$profile_pic'
              WHERE id='$user_id'";
} else {
    $query = "UPDATE users 
              SET first_name='$first_name', last_name='$last_name', address='$address', 
                  city='$city', state='$state', email='$email', phone='$phone'
              WHERE id='$user_id'";
}

if (mysqli_query($conn, $query)) {
    header("Location: ../frontend/account.php?updated=1");
    exit();
} else {
    echo "Error updating profile: " . mysqli_error($conn);
}
?>
