<?php
session_start();

include_once dirname(__DIR__, 2) . "/config/dbcon.php";
include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

try {
    header("Content-Type: application/json");

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    $userId = $_SESSION['user_uid'] ?? null;

    if (!$userId) {
        sendResponse(401, "Unauthorized");
    }

    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if ($name === '' || $email === '' || $phone === '') {
        sendResponse(400, "All fields are required");
    }

    // Fetch existing profile image
    $stmt = $conn->prepare("
        SELECT profile 
        FROM users 
        WHERE firebase_uid = :uid 
        LIMIT 1
    ");
    $stmt->execute([':uid' => $userId]);
    $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$existingUser) {
        sendResponse(404, "User not found");
    }

    $profileImage = $existingUser['profile'];

    // Image upload
    if (!empty($_FILES['profile_image']['name'])) {
        $uploadDir = dirname(__DIR__, 2) . "/uploads/profile/";
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $ext = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (!in_array($ext, $allowed)) {
            sendResponse(400, "Invalid image format");
        }

        $newFileName = "profile_" . time() . "." . $ext;
        $targetPath = $uploadDir . $newFileName;

        move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetPath);

        if ($profileImage && file_exists($uploadDir . $profileImage)) {
            unlink($uploadDir . $profileImage);
        }

        $profileImage = $newFileName;
    }

    // Update user
    $update = $conn->prepare("
        UPDATE users 
        SET name = :name,
            email = :email,
            phone = :phone,
            profile = :profile,
            updated_at = :updated_at
        WHERE firebase_uid = :uid
    ");

    $update->execute([
        ':name' => $name,
        ':email' => $email,
        ':phone' => $phone,
        ':profile' => $profileImage,
        ':updated_at' => date('Y-m-d H:i:s'),
        ':uid' => $userId
    ]);

    sendResponse(200, "Profile updated successfully");

} catch (Exception $e) {
    sendResponse(500, $e->getMessage());
}
