<?php
header('Content-Type: application/json');

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';

session_start();

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    sendResponse(401, "Unauthorized. Please login first.");
}

// Get JSON data
$data = json_decode(file_get_contents("php://input"), true);

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');
$userId = $_SESSION['user_id'];

// Validation
if (!$name || !$email || !$phone) {
    sendResponse(422, "All fields are required.");
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(422, "Invalid email format.");
}

if (!preg_match('/^[0-9]{10,15}$/', $phone)) {
    sendResponse(422, "Phone number must be 10-15 digits.");
}

try {
    // Check if email already exists for another user
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $stmt->execute([$email, $userId]);
    if ($stmt->rowCount() > 0) {
        sendResponse(409, "Email already registered with another account.");
    }

    // Check if phone already exists for another user
    $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ? AND id != ?");
    $stmt->execute([$phone, $userId]);
    if ($stmt->rowCount() > 0) {
        sendResponse(409, "Phone number already registered with another account.");
    }

    // Update user profile
    $stmt = $conn->prepare("UPDATE users SET name = ?, email = ?, phone = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$name, $email, $phone, $userId]);

    if ($stmt->rowCount() > 0 || $stmt->rowCount() === 0) {
        // Update session with new values
        $_SESSION['user_name'] = $name;
        $_SESSION['email'] = $email;
        $_SESSION['user_phone'] = $phone;

        sendResponse(200, "Profile updated successfully!", [
            'user_name' => $name,
            'email' => $email,
            'user_phone' => $phone
        ]);
    } else {
        sendResponse(500, "Failed to update profile.");
    }

} catch (PDOException $e) {
    sendResponse(500, "Database error: " . $e->getMessage());
}
?>