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

// Extra debug: log de volledige POST
file_put_contents('debug-upload-raw.log', print_r([
    'POST' => $_POST,
    'FILES' => $_FILES,
    'TIME' => date('c')
], true) . "\n", FILE_APPEND);

// Normale debug
file_put_contents('debug-upload.log', "SCRIPT REACHED\n", FILE_APPEND);

// === Collect and sanitize inputs ===
$userID = $_POST['userID'] ?? null;
$clientID = $_POST['clientID'] ?? 'default';
$department = $_POST['department'] ?? 'general';

if (!$userID || !isset($_FILES['photo'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing userID or photo']);
    exit;
}

$userID = preg_replace('/[^a-zA-Z0-9_-]/', '', $userID);
$clientID = preg_replace('/[^a-zA-Z0-9_-]/', '', $clientID);
$department = preg_replace('/[^a-zA-Z0-9_.-]/', '', $department);

// === Build destination folder ===
$uploadDir = __DIR__ . "/uploads/$clientID/$department/live/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

// === Handle file ===
$timestamp = time();
$targetPath = $uploadDir . "face_" . $userID . "_" . $timestamp . ".jpg";

if ($_FILES['photo']['error'] !== 0) {
    echo json_encode(['status' => 'error', 'message' => 'Upload error: ' . $_FILES['photo']['error']]);
    exit;
}

if (!move_uploaded_file($_FILES['photo']['tmp_name'], $targetPath)) {
    echo json_encode(['status' => 'error', 'message' => 'Failed to move uploaded file']);
    exit;
}

// === Success ===
file_put_contents('debug-upload.log', json_encode([
    'timestamp' => date('c'),
    'userID' => $userID,
    'clientID' => $clientID,
    'department' => $department,
    'savedTo' => $targetPath,
    'success' => true
]) . "\n", FILE_APPEND);

echo json_encode([
    'status' => 'ok',
    'message' => 'Photo uploaded',
    'image_url' => "https://facecapture.seeyouresto.com/uploads/$clientID/$department/live/face_" . $userID . "_" . $timestamp . ".jpg",
    'timestamp' => $timestamp
]);
?>
