<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';
require_once __DIR__ . '/../../includes/upload.php';

apply_cors();
$authUser = require_user();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $stmt = $pdo->prepare(
        'SELECT id, full_name, email, phone_number, business_name, gst_number, logo_url, photo_url,
                address, website_url, role, license_key, validity_days, activated_at, is_blocked, active_device_id
         FROM users WHERE id = :id'
    );
    $stmt->execute([':id' => $authUser['id']]);
    send_success(['user' => $stmt->fetch()]);
}

if ($method === 'PUT' || $method === 'POST') {
    $isMultipart = str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'multipart/form-data');
    $input = $isMultipart ? $_POST : get_json_input();

    $allowed = ['full_name', 'phone_number', 'business_name', 'gst_number', 'address', 'website_url'];
    $fields = [];
    $params = [':id' => $authUser['id']];
    foreach ($allowed as $f) {
        if (isset($input[$f])) {
            $fields[] = "$f = :$f";
            $params[":$f"] = clean_str($input[$f]);
        }
    }

    if ($isMultipart && isset($_FILES['logo']) && $_FILES['logo']['size'] > 0) {
        $fields[] = 'logo_url = :logo_url';
        $params[':logo_url'] = handle_file_upload('logo', 'profile', ALLOWED_IMAGE_TYPES);
    }
    if ($isMultipart && isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {
        $fields[] = 'photo_url = :photo_url';
        $params[':photo_url'] = handle_file_upload('photo', 'profile', ALLOWED_IMAGE_TYPES);
    }

    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = :id');
    $stmt->execute($params);

    send_success(null, 'Profile updated.');
}

send_error('Invalid request.', 400);
