false, 'message' => 'Method not allowed. Use POST.']); exit; } if (!isset($_FILES['certificate']) || ($_FILES['certificate']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) { http_response_code(422); echo json_encode(['success' => false, 'message' => 'Missing file field: certificate']); exit; } $file = $_FILES['certificate']; $document_name = trim((string)($_POST['document_name'] ?? 'certificato')); if ($document_name === '') $document_name = 'certificato'; $expiry_date = (string)($_POST['expiry_date'] ?? ''); if ($expiry_date === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $expiry_date)) { http_response_code(422); echo json_encode(['success' => false, 'message' => 'expiry_date is required (YYYY-MM-DD)']); exit; } $notes = trim((string)($_POST['notes'] ?? '')); // Allowed extensions $allowed_ext = ['jpg', 'jpeg', 'png', 'pdf', 'heic', 'heif']; $ext = strtolower(pathinfo((string)$file['name'], PATHINFO_EXTENSION)); if (!in_array($ext, $allowed_ext, true)) { http_response_code(422); echo json_encode(['success' => false, 'message' => 'Unsupported format. Allowed: jpg, jpeg, png, pdf, heic, heif']); exit; } if ((int)$file['size'] > 10 * 1024 * 1024) { http_response_code(422); echo json_encode(['success' => false, 'message' => 'File too large (max 10MB)']); exit; } // Upload dir: ../certificate relative to /public/userarea/api $upload_dir = realpath(__DIR__ . '/..') . DIRECTORY_SEPARATOR . 'certificate' . DIRECTORY_SEPARATOR; if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); } $safe_name = preg_replace('/[^a-zA-Z0-9\._-]/', '_', basename((string)$file['name'])); $new_filename = $iduserlogin . '-' . time() . '-' . $safe_name; $destination = $upload_dir . $new_filename; if (!move_uploaded_file((string)$file['tmp_name'], $destination)) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Error saving the file.']); exit; } $stored_path = 'userarea/certificate/' . $new_filename; // OPTIONAL: if you later add school_id column, include it here too. $stmt = $pdo->prepare(" INSERT INTO user_medical_certificates (user_id, filename, stored_path, document_name, expiry_date, notes, uploaded_at) VALUES (?, ?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $iduserlogin, (string)$file['name'], $stored_path, $document_name, $expiry_date, $notes ]); $newId = (int)$pdo->lastInsertId(); echo json_encode([ 'success' => true, 'certificate' => [ 'id' => $newId, 'document_name' => $document_name, 'filename' => (string)$file['name'], 'stored_path' => $stored_path, 'file_url' => '/' . $stored_path, 'expiry_date' => $expiry_date, 'notes' => $notes !== '' ? $notes : null ] ], JSON_UNESCAPED_UNICODE); } catch (Throwable $e) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Server error.', 'error' => $e->getMessage()]); }