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

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

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

if (!isset($_SESSION['user_id'])) {
    sendResponse(401, "Unauthorized");
}

if (!isset($_FILES['profile_image'])) {
    sendResponse(422, "No image uploaded");
}

$file = $_FILES['profile_image'];

// Validate upload
if ($file['error'] !== UPLOAD_ERR_OK) {
    sendResponse(400, "Upload failed");
}

// Allowed types
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);

if (!in_array($mimeType, $allowedTypes)) {
    sendResponse(422, "Invalid image type");
}

// Max size 2MB
if ($file['size'] > 2 * 1024 * 1024) {
    sendResponse(422, "Image must be less than 2MB");
}

// Create upload directory
$uploadDir = __DIR__ . '/../../uploads/profile/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Generate unique filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = 'user_' . $_SESSION['user_id'] . '_' . time() . '.' . $extension;
$filepath = $uploadDir . $filename;

// Move file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
    sendResponse(500, "Failed to save image");
}

// Save path in DB
$imagePath = $filename;

$_SESSION['profile_image'] = $imagePath;

$stmt = $conn->prepare("UPDATE users SET profile = ? WHERE id = ?");
$stmt->execute([$imagePath, $_SESSION['user_id']]);

sendResponse(200, "Profile image updated successfully", [
    'image_url' => $_ENV['BASE_URL'] ?? '/' . $imagePath
]);
