<?php
session_start();
require 'config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    sendResponse(false, 'User not logged in', null);
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch user profile data
    $user_id = $_SESSION['user_id'];
    $sql = "SELECT id, name, email, phone, created_at FROM users WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        sendResponse(true, 'User profile fetched successfully', $user);
    } else {
        sendResponse(false, 'User not found', null);
    }
    $stmt->close();
} 
elseif ($method === 'POST') {
    // Update user profile data
    $user_id = $_SESSION['user_id'];
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    
    // Validation
    if (empty($name)) {
        sendResponse(false, 'Name is required', null);
    }
    
    if (strlen($name) < 2) {
        sendResponse(false, 'Name must be at least 2 characters long', null);
    }
    
    if (strlen($name) > 100) {
        sendResponse(false, 'Name must not exceed 100 characters', null);
    }
    
    if (!empty($phone) && !preg_match('/^[0-9\+\-\(\)\s]{7,20}$/', $phone)) {
        sendResponse(false, 'Invalid phone number format', null);
    }
    
    // Update database
    $sql = "UPDATE users SET name = ?, phone = ?, updated_at = NOW() WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $name, $phone, $user_id);
    
    if ($stmt->execute()) {
        // Update session and localStorage
        $_SESSION['user_name'] = $name;
        sendResponse(true, 'Profile updated successfully', [
            'id' => $user_id,
            'name' => $name,
            'phone' => $phone
        ]);
    } else {
        sendResponse(false, 'Failed to update profile: ' . $conn->error, null);
    }
    $stmt->close();
}

$conn->close();
?>
